我编写了一个代码来创建数据文件。在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 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;
}
答案 0 :(得分: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;
}
正如您所看到的,我使用perror可以在fopen
函数发生错误时添加信息。