C语言中的文件I/O——如何从文件中读取然后写入



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

当打开文件进行读写操作时,在操作之间切换时会使用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

在读写之后,它包含

01234 fghij56789pqrstuvwxyz

最新更新