需要帮助解决C中文件I/O的分段错误 [英] need help solving a segmentation fault with file i/o in C

查看:59
本文介绍了需要帮助解决C中文件I/O的分段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读取了具有911行的输入文件,并希望在对每行进行一些更改之后将这些911行复制到输出文件中..

I read the input file , which has 911 lines , and want to copy these 911 lines into the output file , after making a few changes to each line..

我运行此程序时出现细分错误..我不知道为什么..任何人都可以帮忙..

I am getting segmentation fault when i run this.. I dont know why.. can anyone please help..

#include<stdio.h>
void main()
{
    int i;
    FILE *fin,*fop;char* str;
    fin=fopen("atk561011.txt","r");
    if(fin=NULL) printf("ip err");
    fop=fopen("svmip.txt","w");
    if(fop=NULL) printf("op err");
    for(i=1;i<=911;i++)
    {
        fgets(str,150,fin);
        if((i>300&&i<=360)||(i>600&&i<=660)) 
            str[7]='1';
        else 
            str[7]='0';
        fputs(str+7,fop);
        putc('\n',fop);
    }
    fclose(fin);
    fclose(fop);
}

推荐答案

首先,这是错误的:

if(fin=NULL)

应该是:

if (fin == NULL)

(当然,fop也是如此).而且,如果您未成功打开文件-不要仅打印错误,请退出,因为您将从中读取什么?请记住,printf的输出是经过缓冲的,如果发生段错误,即使它在故障之前运行,您也将永远不会看到它.

(the same goes for fop, of course). And if you didn't succeed opening the file - don't just print an error, exit, because what are you going to read from? Keep in mind that the output of printf is buffered and in case of a segfault you won't always see it at all, even if it ran before the fault.

另一件事:您没有为str分配内存,而是使用fgets写入内存.

Another thing: you don't allocate memory for str, yet write into it with fgets.

还有另一件事:从文件中读取预定义的行数可能是个坏主意.最好从输入中读取,直到文件结束,或者直到读取了所需的行数为止.

And another thing: reading a pre-defined amount of lines from the file is probably a bad idea. It's better to read from the input until there is an end of file, or until a required amount of lines has been read.

这篇关于需要帮助解决C中文件I/O的分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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