简体   繁体   English

使用fgets从文件读取段错误错误

[英]Seg Fault error reading from file with fgets

//declare double pointer so that create array can "return" an array
int **aryReturn;
int size;
char trashdata[100];

//open file
FILE *inFilePtr = fopen(*(argv + 1), "r" );

if (inFilePtr != NULL)
    printf(" the value of argv 1 is %s \n", argv[1]); 

while (fgets(trashdata, sizeof(int) * 10, inFilePtr) != NULL){
    fgets(trashdata, 10, inFilePtr);
    size++;
}

can anyone tell me why my loop condition will not work! 谁能告诉我为什么我的循环条件不起作用! I get a seg fault that says fp(0x0) at fgets. 我在fgets遇到段错误,提示fp(0x0)。 I have tried 我努力了

while (!feof(inFilePtr))

And I basically get the same error, but it says feof is the problem. 而且我基本上得到了相同的错误,但是它说feof是问题所在。

My file seems to open correctly because the if statement prints.. and argv has the expected file name 我的文件似乎正确打开,因为if语句打印了..并且argv具有预期的文件名

Well, I see a few problems... 好吧,我看到了一些问题...

  • size is not initialized size未初始化
  • calling gets() twice in a row seems odd, see feof() 连续两次调用gets()似乎很奇怪,请参阅feof()
  • you aren't doing anything after testing the fopen() result against NULL, so the first gets() could bomb out for that reason ... do you get that message? 在针对NULL测试了fopen()结果之后,您什么也不做,因此第一个gets()可能会因为这个原因而被炸毁……您是否得到了该消息?

Only the last thing seems likely to throw an exception, but my philosophy is always fix the known problems and retest ... it's a waste of time to predict interactions between bugs. 似乎只有最后一件事可能会引发异常,但是我的理念始终是修复已知问题并重新测试 ...预测错误之间的交互是浪费时间。

I think that the filename that you are providing in the argument either does-not exists or some access violations. 我认为您在参数中提供的文件名不存在或存在某些访问冲突。 You can check this by printing the errno just after doing the fopen command. 您可以在执行fopen命令之后通过打印errno进行检查。

fprintf (stderr, "Couldn't open file %s; %s\n", argv[1], strerror (errno));

also can you try this code once: 您也可以尝试一下此代码:

#include<errno.h>
#include<stdio.h>
int main(int argc, char **argv)
{
    int **aryReturn;
    int size=0;
    char trashdata[100];

    //open file
    FILE *inFilePtr = fopen(*(argv + 1), "r" );

    printf(" the value of argv 1 is %s \n", argv[1]);
    if (inFilePtr == NULL)
    {
        fprintf (stderr, "Couldn't open file %s; %d\n", argv[1],errno);
        exit(0);
    }
    while (!feof(inFilePtr)){
    fgets(trashdata, 10, inFilePtr);
    printf("%s",trashdata);
    size++;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM