c - fopen() 总是返回 NULL

标签 c

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/

相关文章:

c++ - 加密和解密部分 ASCII 表

使用二维数组转换为列主方式

c - 如何向字符添加字符

c++ - 错误 C2228 : left of '.DXGI_MODE' must have class/struct/union Direct X

c - WIX CustomAction C#

c++ - 对齐和SSE异常行为

c - 如何从一定范围内生成随机整数

在 C 中关闭文件

对 C 中的指针和泛型(void)指针感到困惑

c - 套接字中的网络字节顺序