46

我希望我的程序打开一个文件(如果存在),或者创建该文件。我正在尝试以下代码,但我在 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);
    } 
4

2 回答 2

64

您通常必须在单个系统调用中执行此操作,否则您将获得竞争条件。

这将打开读取和写入,必要时创建文件。

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);
于 2012-03-23T14:11:45.123 回答
10

如果fptrNULL,那么您没有打开的文件。因此,你做不到freopen,你应该fopen这样做。

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

注意:由于您的程序的行为取决于文件是以读取还是写入模式打开,因此您很可能还需要保留一个变量来指示是哪种情况。

一个完整的例子

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;
}
于 2012-03-23T14:12:05.310 回答