fgets()的分段错误

时间:2014-01-23 07:14:31

标签: c

以下代码给出了分段错误。我还尝试使用malloc来分配str。我无法避免分段错误。请帮忙。

#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>

int main() {
    int fd = open("/home/pdave/hello2.c", O_RDONLY);
    FILE* stream;
    stream = fopen("./home/pdave/hello2.c", "r");
    char lin[128];
    int ret = 0;
    int cnt = 0;
    char str[128];
    while((fgets(str, 128, stream)) != NULL) {
        printf("%d\t%d\t%s", cnt, ret, str);    
    }
}

2 个答案:

答案 0 :(得分:3)

您只能使用fopen()打开文件,因此请删除第一个文件:

int fd = open("/home/pdave/hello2.c", O_RDONLY);

fopen()函数中的文件路径似乎错了:

stream = fopen("/home/pdave/hello2.c","r");

答案 1 :(得分:1)

当文件路径错误时,fopen的返回值将为NULL。

fgets使用NULL会导致SO

您的文件路径看起来不对,通常不会有像./home/path这样的路径。

fopen之后将NULL的返回值与fopen进行比较。

尝试:

stream = fopen("/home/pdave/hello2.c", "r");
if (stream == NULL) {
    printf("Error opening file\n");
    return -1;
}

进一步man fopenman fgets