C 无法使用代码块创建数据文件
我已经写了一段代码来创建一个数据文件。在if-else块中,执行else块,但不会在所需位置创建文件。为什么会这样C 无法使用代码块创建数据文件,c,file,codeblocks,C,File,Codeblocks,我已经写了一段代码来创建一个数据文件。在if-else块中,执行else块,但不会在所需位置创建文件。为什么会这样 #include <stdio.h> int main() { FILE *fptr; fptr = fopen("C:\\test.txt", "w"); if(fptr == NULL) // codition when file is not created { printf("File can not be create
#include <stdio.h>
int main() {
FILE *fptr;
fptr = fopen("C:\\test.txt", "w");
if(fptr == NULL) // codition when file is not created
{
printf("File can not be created. \n");
}
else
{
printf("file has been successfully created. \n");
}
//fputs(string, file_pointer_variable)
fputs("my first write to file", fptr);
fclose(fptr);
return 0;
}
#包括
int main(){
文件*fptr;
fptr=fopen(“C:\\test.txt”,“w”);
if(fptr==NULL)//未创建文件时的密码
{
printf(“无法创建文件。\n”);
}
其他的
{
printf(“文件已成功创建。\n”);
}
//fputs(字符串、文件\指针\变量)
fputs(“我第一次写入文件”,fptr);
fclose(fptr);
返回0;
}
您的问题可能属于在c:\
如果fopen
失败,必须更改代码以避免使用该文件,例如:
#include <stdio.h>
int main(void)
{
FILE *fptr;
fptr = fopen("C:\\test.txt", "w");
if(fptr == NULL) // codition when file is not created
{
perror("fopen error: ");
return 1;
}
else
{
printf("file has been successfully created. \n");
fputs("my first write to file", fptr);
fclose(fptr);
}
return 0;
}
#包括
内部主(空)
{
文件*fptr;
fptr=fopen(“C:\\test.txt”,“w”);
if(fptr==NULL)//未创建文件时的密码
{
perror(“fopen错误:”);
返回1;
}
其他的
{
printf(“文件已成功创建。\n”);
fputs(“我第一次写入文件”,fptr);
fclose(fptr);
}
返回0;
}
正如您所看到的,我使用了一个可以添加有关使用
fopen
函数时发生错误的信息的工具。您确定有权在`c:\`中创建文件吗?此外,如果创建失败,您应该终止您的程序或避免执行puts等以获得帮助。我更改了文件的目录/位置,它工作了。