這是我的代碼不會創建txt文件C程序
#include <stdio.h>
int main()
{
FILE *file;
file = fopen("file.txt","a+");
fprintf(file,"%s","test :)");
fclose(file);
return 0;
}
不明白爲什麼它不會創建一個txt文件 幫助
這是我的代碼不會創建txt文件C程序
#include <stdio.h>
int main()
{
FILE *file;
file = fopen("file.txt","a+");
fprintf(file,"%s","test :)");
fclose(file);
return 0;
}
不明白爲什麼它不會創建一個txt文件 幫助
您需要檢查程序中的錯誤。由於各種原因,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][[email protected] /tmp] ./foo
Failed to open the file: Permission denied
我嘗試它,但它仍然無法與if循環工作,但IETS打印什麼,所以我不知道T.T我已經premission我認爲 – SamSam
Create a file if one doesn't exist - C 這裏有答案......而其中,根據一個標記的工作對我來說就這樣你試圖做的方式在Windows上不起作用,但在linux上工作。對不起,我之前說過的話......兩種操作系統都有明亮而不那麼明亮的一面。
錯在何處?如果你單步執行,會發生什麼?添加代碼來檢查'fopen()'是否成功,I/O可能會失敗。 – unwind
適用於我 – akappa
'a +'模式的預期行爲是在文件不存在的情況下創建文件。在這裏,我的直覺是,'fopen()函數調用'爲特定原因而失敗(是的,它可能會失敗所以總是檢查返回值...) – Rerito