0

这是我的代码

#include <stdio.h> 
int main() 
{ 
FILE *file; 
file = fopen("file.txt","a+"); 

fprintf(file,"%s","test :)");
fclose(file); 

return 0; 
}

不明白为什么它不会创建一个txt文件帮助

4

3 回答 3

1

您需要检查程序中的错误。fopen()可能由于各种原因而失败。我们可以检查errno,或者使用perror / strerror来打印有用的消息。

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

int main() 
{ 
    FILE *file = fopen("file.txt","a+"); 
    if (file == NULL) {
        perror("Failed to open the file");
        exit(-1);
    }

    fprintf(file,"%s","test :)");
    fclose(file); 

    return 0; 
}

例如,如果一个文件存在于当前目录中,但属于不同的用户:

[8:40am][wlynch@watermelon /tmp] ./foo
Failed to open the file: Permission denied
于 2013-10-31T13:41:03.247 回答
1

请尝试 perror 检查您是否有权写入文件。这是大多数时候的问题。在 fopen 之后添加这个

if (!file)
perror("fopen");
于 2013-10-31T13:39:38.140 回答
0

如果一个文件不存在,则创建一个文件-C 这里是答案...标记下的那个对我有用,所以您尝试做的方式在 Windows 上不起作用,但在 linux 上有效。抱歉说了我之前说过的话……这两个操作系统都有其光明的一面,而不是那么光明的一面。

于 2017-11-03T20:14:20.067 回答