我希望我的程序打开文件(如果存在),或者创建文件。我正在尝试以下代码,但我在freopen.c上得到一个调试断言。我会更好地使用fclose然后立即fopen吗?
FILE *fptr;
fptr = fopen("scores.dat", "rb+");
if(fptr == NULL) //if file does not exist, create it
{
freopen("scores.dat", "wb", fptr);
}
答案 0 :(得分:51)
您通常必须在一个系统调用中执行此操作,否则您将遇到竞争条件。
这将打开进行读写,必要时创建文件。
FILE *fp = fopen("scores.dat", "ab+");
如果您想阅读它然后从头开始编写新版本,那么请分两步完成。
FILE *fp = fopen("scores.dat", "rb");
if (fp) {
read_scores(fp);
}
// Later...
// truncates the file
FILE *fp = fopen("scores.dat", "wb");
if (!fp)
error();
write_scores(fp);
答案 1 :(得分:9)
如果fptr
是NULL
,那么您没有打开的文件。因此,你不能freopen
它,你应该fopen
它。
FILE *fptr;
fptr = fopen("scores.dat", "rb+");
if(fptr == NULL) //if file does not exist, create it
{
fptr = fopen("scores.dat", "wb");
}
note :由于程序的行为会根据文件是以读取还是写入方式打开而有所不同,因此您很可能还需要保留一个变量来指示是哪种情况。
int main()
{
FILE *fptr;
char there_was_error = 0;
char opened_in_read = 1;
fptr = fopen("scores.dat", "rb+");
if(fptr == NULL) //if file does not exist, create it
{
opened_in_read = 0;
fptr = fopen("scores.dat", "wb");
if (fptr == NULL)
there_was_error = 1;
}
if (there_was_error)
{
printf("Disc full or no permission\n");
return EXIT_FAILURE;
}
if (opened_in_read)
printf("The file is opened in read mode."
" Let's read some cached data\n");
else
printf("The file is opened in write mode."
" Let's do some processing and cache the results\n");
return EXIT_SUCCESS;
}