简体   繁体   English

尝试测试fgets()时出现分段错误

[英]Segmentation fault while trying to test fgets()

I'm trying to write a program to experiment with the fgets() function, with which I have little experience. 我正在尝试编写一个程序来尝试fgets()函数,对此我几乎没有经验。 I keep getting a segmentation fault 11 error when I run the program (but no errors when I compile it) and I don't know enough about fgets to know what is going on. 运行程序时,我始终遇到分段错误11错误(但编译时没有错误),而且我对fgets的了解还不足以了解发生了什么。 Here is my program: 这是我的程序:

#include <stdio.h>

int main (void) {
    FILE *fp;
    fp = fopen("wageData.txt","r+");
    char x[3][5];
    int i = 0;
    while (i < 3) {
        fgets(x[i], 4, fp);
        i++;
    }

    for (i = 0; i < 3; i++) {
        printf("%s\n", x[i]);
    }

    return 0;
}

Here is the text file that I have linked to it: 这是我链接到的文本文件:

Hi, my name is Frank.  
I like pie.  
My car is black.

I have built and executed your code with your suggested data, and it executes without error. 我已经使用建议的数据构建并执行了您的代码,并且执行时没有错误。 However, you do not check that the call to fopen() is successful, and if fp is not a valid open file pointer, it does indeed abort. 但是,您不会检查对fopen()的调用是否成功,并且如果fp不是有效的打开文件指针,则确实会中止。

I suspect in that case that the file was not opened; 在这种情况下,我怀疑文件没有打开; perhaps it was not in the current working path, was incorrectly named (POSIX file-systems for example are case sensitive), or was other wise locked (perhaps open elsewhere). 也许它不在当前工作路径中,或者被错误命名(例如,POSIX文件系统区分大小写),或者被其他方式锁定(也许在其他地方打开)。

Equally it would be wise to check the success of fgets() so that it will work with files shorter then three lines: 同样,检查fgets()是否成功是明智的,这样它就可以处理短于三行的文件:

#include <stdio.h>

int main(void) 
{
    FILE *fp = fopen("wageData.txt", "r+");
    if( fp != 0 )
    {
        char x[3][5];
        int i = 0;
        int j ;
        char* check = 0 ;
        while( i < 3 && fgets(x[i], 4, fp) != 0 ) 
        {
            i++;
        }

        for( j = 0; j < i; j++) 
        {
            printf("%s\n", x[j]);
        }
    }
    else
    {
        printf( "File not opened.\n" ) ;
    }

    return 0;
}

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

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