本文介绍了调用 fgets 时出现分段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试编写一个简单的程序来从纯文本列表中列出的文件中读取数据,但是当我尝试在我的 processFile 函数中调用 fgets() 时,我一直遇到分段错误.
I'm trying to write a simple program to read data from files listed in a plain text list, but I keep running into a segmentation fault when I try to call fgets() in my processFile function.
如果我只是简单地调用类似 processFile("file.txt") 的东西就不会发生这种情况,但是当我尝试通过我的 processList 函数调用 processFile 时会发生这种情况.
It doesn't happen if I were to simply call something like processFile("file.txt"), but it happens when I try to call processFile through my processList function.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void processFile (char *file)
{
char line[256];
FILE* pgmFile;
pgmFile = fopen(file, "r");
fgets(line, 200, pgmFile); // Seg fault here
fclose(pgmFile);
}
// Runs processFile on every file listed in list
void processList (char *list)
{
FILE *pgmList;
pgmList = fopen(list, "r");
char line[256];
while (fgets(line, 255, pgmList) != NULL) {
processFile(line);
}
fclose(pgmList);
}
int main ()
{
processList("downgesture_test1.list");
}
推荐答案
尝试检查 fopen
的返回值.如果它是 NULL
怎么办?因为您的文件名"很可能有尾随 .
Try checking return value of fopen
. What if it's NULL
? Because it is likely that your "file name" has trailing .
这篇关于调用 fgets 时出现分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!