Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
韩元';创建txt文件的C程序_C_File - Fatal编程技术网

韩元';创建txt文件的C程序

韩元';创建txt文件的C程序,c,file,C,File,这是我的密码 #include <stdio.h> int main() { FILE *file; file = fopen("file.txt","a+"); fprintf(file,"%s","test :)"); fclose(file); return 0; } #包括 int main() { 文件*文件; file=fopen(“file.txt”,“a+”); fprintf(文件“%s”,“测试:”); fclose(文件); 返回0; }

这是我的密码

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

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

return 0; 
}
#包括
int main()
{ 
文件*文件;
file=fopen(“file.txt”,“a+”);
fprintf(文件“%s”,“测试:”);
fclose(文件);
返回0;
}
不明白为什么它不会创建txt文件
帮助

请尝试或检查您是否具有写入该文件的权限。这是大多数时候的问题。将此添加到fopen之后

if (!file)
perror("fopen");

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

#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; 
}

下面是答案…在标记的下面的一个在我的s.o上为我工作。你尝试的方式在windows上不起作用,但在linux上起作用。很抱歉说了我之前说过的话……两种操作系统都有其光明和不那么光明的一面。

出了什么问题?如果执行过程中只执行一步,会发生什么情况?添加代码以检查
fopen()
是否成功,I/O是否可能失败。
a+
模式的预期行为是创建不存在的文件。我的直觉是,
fopen()
调用由于特定的原因失败(是的,它可能会失败,所以总是检查返回值…)检查您当前的工作目录(查找getcwd并打印它或其他内容)。我的猜测是,您可能没有它试图在其中创建file.txt的文件夹的完全权限,但正如下面的家伙所说,它可能是任何数量的东西。如果要更改当前工作目录,请在fopen之前使用chdir,或者在fopen中硬编码所需的目录,如fopen(“C://users/me/documents/file.txt”,“a+”);昨天它工作,但今天不再。。。我什么也没做…我尝试了一下,但它仍然不能与if循环一起工作,但是让我们什么也不打印,所以我不知道T。T如果您使用的是Visual Studio,只需在
FILE*FILE=fopen(“FILE.txt”,“a+”)上加一个断点即可并调试它。当光标越过这条线时,查看“监视”窗口中的文件发生了什么,然后在此处更新我我尝试了它,但它仍然不能与if循环一起工作,但让它不打印任何内容,所以我不知道T。我想我有预任务
[8:40am][wlynch@watermelon /tmp] ./foo
Failed to open the file: Permission denied