【问题标题】:File I/O in C - How to read from a file and then write to it?C 中的文件 I/O - 如何从文件中读取然后写入文件?
【发布时间】:2015-08-06 06:12:22
【问题描述】:

我是 C 文件 i/o 的新手,在我的代码中,我想从文本文件中读取信息,然后写入它。 我尝试使用 fopen("file.csv", "r+t") 打开一个 csv 文件,以便能够读取然后写入同一个文件。所以我使用了 fgetc,然后使用了 fputc,但由于某种原因,fputc 函数不起作用。当我尝试切换顺序时,该字符被毫无问题地打印到文件中,但看起来 fgetc 在下一个位置放置了一个未知字符。 我做错了什么,还是实际上不可能在同一个流中读取和写入文件?感谢您的帮助!

【问题讨论】:

  • 发布您的代码。
  • 如果它是一个文本文件,您最好编写一个新版本的文件。假设您想用"123," 替换片段"1234,"。你怎么处理多余的字符?同样反过来,你会把多余的字符放在哪里?文件上的 R/W 更适合二进制格式,其中(比如)int 值 123 与 1234 占用相同数量的字节,因此可以轻松覆盖。
  • 谢谢user3121023,显然这是问题所在

标签: c file-io fopen fgetc


【解决方案1】:

当打开文件进行读写时,在操作之间切换时会使用 fseek()。 fseek( fp, 0, SEEK_CUR); 不会改变文件指针在文件中的位置。

#include<stdio.h>
#include<stdlib.h>

int main ( ) {
    int read = 0;
    int write = 48;
    int each = 0;
    FILE *fp;

    fp = fopen("z.txt", "w");//create a file
    if (fp == NULL)
    {
        printf("Error while opening the file.\n");
        return 0;
    }
    fprintf ( fp, "abcdefghijklmnopqrstuvwxyz");
    fclose ( fp);

    fp = fopen("z.txt", "r+");//open the file for read and write
    if (fp == NULL)
    {
        printf("Error while opening the file.\n");
        return 0;
    }

    for ( each = 0; each < 5; each++) {
        fputc ( write, fp);
        write++;
    }
    fseek ( fp, 0, SEEK_CUR);//finished with writes. switching to read

    for ( each = 0; each < 5; each++) {
        read = fgetc ( fp);
        printf ( "%c ", read);
    }
    printf ( "\n");
    fseek ( fp, 0, SEEK_CUR);//finished with reads. switching to write

    for ( each = 0; each < 5; each++) {
        fputc ( write, fp);
        write++;
    }
    fseek ( fp, 0, SEEK_CUR);//finished with writes. switching to read

    for ( each = 0; each < 5; each++) {
        read = fgetc ( fp);
        printf ( "%c ", read);
    }
    printf ( "\n");

    fclose ( fp);
    return 0;
}

输出
该文件最初包含

abcdefghijklmnopqrstuvwxyz

读写后包含

01234fghij56789pqrstuvwxyz

【讨论】:

  • 不应该是 SEEK_SET 设置回文件的开头而不是 SEEK_CUR (RELATIVE TO CURRENT CURSOR)
猜你喜欢
  • 2020-07-18
  • 2011-06-10
  • 2023-04-05
  • 1970-01-01
  • 1970-01-01
  • 2020-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多