阅读在C文件:为&QUOT不同的行为; R"和" A + QUOT;旗 [英] Reading a File in C: different behavior for "r" and "a+" flags

查看:131
本文介绍了阅读在C文件:为&QUOT不同的行为; R"和" A + QUOT;旗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想打开一个文件,阅读其内容,然后追加一行到文件中。我想我应该用a +标志的任务。

I want to open a file, read its contents, and then append a line to the file. I thought I should use the "a+" flag for the task.

我打开一个文件,并返回一个指向该文件的功能。

I have a function which opens a file and returns a pointer to this file.

FILE* open_weekly_disk_file(char* filename){
    FILE* weekly_log;

    weekly_log = fopen(filename, "a+");
    //weekly_log = fopen(filename, "r");

    if(! weekly_log){
        printf("The attempt to open the weekly log failed!\n");
        return NULL;
    } else{
        return weekly_log;
    }
}

然后我有一个调用上面的功能和使用scanf函数读取文件内容的函数:

Then I have a function which calls the function above and uses scanf to read contents from the file:

void sample_function(char* filename){
    FILE* log;
    char token[100], current_read[100];
    int limit;

    log = opened_weekly_disk_file(filename);
    // The problem happens here
    for(limit=0; limit < TOKEN_NUMBER; limit++){
        if(fscanf(log, "%s%s", &token, &current_read) == 2){
            printf("%s %s\n", token, current_read);
        }
    }
    ...
}

这code工作当我使用:

This code works when I use:

weekly_log = fopen(filename, "r");

但是,当我改变R标志A +不起作用。我前右for循环得到一个分段错误。

But does not work when I change the "r" flag to "a+". I get a Segmentation fault right before the for loop.

推荐答案

这是因为模式规范打开附加的文件,与文件指针结束。如果试图从这里看,没有数据,因为文件指针是EOF。你应该打开R +进行读取和写入。如果你读写入之前整个文件,那么该文件指针会在正确的位置,当你写更多的数据追加。

That is because the mode spec "a" opens a file for appending, with the file pointer at the end. If you try to read from here, there is no data since the file pointer is at EOF. You should open with "r+" for reading and writing. If you read the whole file before writing, then the file pointer will be correctly positioned to append when you write more data.

如果这还不够,请浏览 FTELL() fseek的()功能。

If this is not enough, please explore ftell() and fseek() functions.

这篇关于阅读在C文件:为&QUOT不同的行为; R&QUOT;和&QUOT; A + QUOT;旗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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