创建一个文件,如果不存在 - Ç [英] Create a file if one doesn't exist - C

查看:205
本文介绍了创建一个文件,如果不存在 - Ç的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想我的程序打开一个文件,如果它存在,否则,创建文件。我想下面的code,但我发现在freopen.c调试断言。我会过得更好使用FCLOSE然后FOPEN随即?

  FILE * FPTR;
    FPTR =的fopen(scores.dat,RB +);
    如果(FPTR == NULL)//如果文件不存在,创建它
    {
        freopen函数(scores.dat,白平衡,FPTR);
    }


解决方案

您通常必须这样做在一个单一的系统调用,否则你会得到一个竞争条件。

这将打开阅读和写作,如果有必要创建文件。

  FILE *计划生育=的fopen(scores.dat,AB +);

如果你想读它,然后从头开始编写一个新的版本,然后再去做两个步骤。

  FILE *计划生育=的fopen(scores.dat,RB);
如果(FP){
    read_scores(FP);
}//后来...//截断文件
FILE *计划生育=的fopen(scores.dat,世行);
如果(!FP)
    错误();
write_scores(FP);

I want my program to open a file if it exists, or else create the file. I'm trying the following code but I'm getting a debug assertion at freopen.c. Would I be better off using fclose and then fopen immediately afterward?

FILE *fptr;
    fptr = fopen("scores.dat", "rb+");
    if(fptr == NULL) //if file does not exist, create it
    {
        freopen("scores.dat", "wb", fptr);
    } 

解决方案

You typically have to do this in a single syscall, or else you will get a race condition.

This will open for reading and writing, creating the file if necessary.

FILE *fp = fopen("scores.dat", "ab+");

If you want to read it and then write a new version from scratch, then do it as two steps.

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);

这篇关于创建一个文件,如果不存在 - Ç的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆