Ofir
Ofir

Reputation: 138

File I/O in C - How to read from a file and then write to it?

I'm new to file i/o in C, and in my code I want to read information from a text file and then write to it. I tried to open a csv file using fopen("file.csv", "r+t") in order to be able to read and then write to the same file. So I used fgetc and then fputc, but for some reason, the fputc function didn't work. When I tried to switch the order, the character was printed to the file without a problem, but it looks as the fgetc has put an unknown character in the next spot. Am I doing something wrong, or is it actually impossible to read and write to a file at the same stream? Thanks for helping!

Upvotes: 1

Views: 3882

Answers (1)

user3121023
user3121023

Reputation: 8308

When a file is opened for read and write, an fseek() is used when switching between operations. fseek( fp, 0, SEEK_CUR); does not change the position of the file pointer in the file.

#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;
}

output
the file initially contained

abcdefghijklmnopqrstuvwxyz

after the read and write, it contains

01234fghij56789pqrstuvwxyz

Upvotes: 2

Related Questions