int main()
{
int i;
FILE *list,*file;
char temp[30];
list=fopen("filelist","rb");
while(fgets(temp,30,list)!=NULL)
{
file=fopen(temp,"r");
{
fclose(list);
return 0;
}
这是我的代码,我基本上想打开文件列表中的所有文件,但我的 fopen 调用(除了第一个总是返回 NULL,我是否遗漏了一些东西,这也是我的文件列表
file1
file2
file3
file4
我也不使用文件扩展名,并且文件与可执行文件存在于同一目录中。
最佳答案
fgets()
将换行符存储到它正在填充的缓冲区中,因此您需要在 while
中调用 fopen()
之前将其删除。
来自 fgets()
的链接引用页:
Reads at most count - 1 characters from the given file stream and stores them in str. The produced character string is always NULL-terminated. Parsing stops if end-of-file occurs or a newline character is found, in which case str will contain that newline character.
删除换行符的示例代码:
char* nl = strrchr(temp, '\n');
if (nl) *nl = 0;
关于c - fopen() 总是返回 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13900854/