写入文件会出现错误segmentaion错误 [英] writting to file gives error segmentaion fault

查看:78
本文介绍了写入文件会出现错误segmentaion错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

        ofstream f;
char c;
f.close();
f.open(s.c_str(),ios::out);
if(f.is_open()) {
cout<<"Press <q> to save file";
char *text;
int count=0,count1;

while(1)
{   system("stty raw -echo");
    cin>>c;
    cout<<c;
    system("stty cooked echo");
    text[count]=c;
    ++count;

        if(c==''q'')
    {
            text[count]=''\0'';
                while (text[count1]!=''\0'')
        f.put(text[count1++]);
    f.close();
            break;
                }
        }



请以这种语法帮助我,我无法在文件中写入数据
为什么这段代码会导致分段错误
我该如何解决这个问题

[edit]已添加代码块-OriginalGriff [/edit]



please help me out in this syntax i was not able to write data in file
Why this code gives segmentation fault
how i can resolve this problem

[edit]Code Block added - OriginalGriff[/edit]

推荐答案

不,您将无法编写.

您是要列出错误列表,还是要报告的问题?

然后只有一个:
No, you won''t be able to write.

Do you want a list of errors, or just the problem you are reporting?

Just the one then:
char *text;
        ....
text[count]=c;

访问元素"count"时"text"指向何处?您赋予它什么价值?为其分配了多少个元素?

很好,这是关于另一种的提示,当您修复该提示时:

Where is "text" pointing when you access element "count"? What value have you given it? How many elements are allocated to it?

And just to be nice, here is hint about another one for when you fix that one:

while(1)

不是循环,您永远都不会摆脱......

is not a loop you will ever get out of...


text[count]=c;



文本很可能不会指向任何可写内存,因为您尚未分配或分配任何可写内存.我建议您使用调试器来轻松发现这些问题.



text does most likely not point to any writable memory since you have not assigned or allocated any. I suggest you use the debugger to easily spot these problems.


除了其他人已经指出的以外,count1被用作数组的索引而无需初始化...尽管数组根本没有分配,因此直到您先清除一个数组,问题才会出现.
Besides what others have already pointed out, count1 is being used as an index into the array without being initialized... although the array isn''t allocated at all so that problem won''t come up until you clear that one up first.


这篇关于写入文件会出现错误segmentaion错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆