user6274708
user6274708

Reputation:

Data is appended to end of file instead of the specified offsets

I am working with 4 files and want to inject a string at a specified offset to each one of them.I am using fseek() but the data is being written to the end of files instead of intended offsets.Why, and how can i fix it:

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

#define SZ 14
#define TARGET_NUM 4

long GetFileSize(FILE *fp);

int main(void)
{
    long offset[TARGET_NUM] = { 10,15,20,25 };

    const char *file_names[TARGET_NUM] = {
                                             "file1.txt", "file2.txt",
                                             "file3.txt", "file4.txt",
                                         };


    char dat[TARGET_NUM][SZ + 1] = {
                                       { '1','0','0','0','0','0','0','0', '0','0','0','0','0','0', 0 },
                                       { '0','1','0','0','0','0','0','0', '0','0','0','0','0','0', 0 },
                                       { '0','0','1','0','0','0','0','0', '0','0','0','0','0','0', 0 },
                                       { '0','0','0','1','0','0','0','0', '0','0','0','0','0','0', 0 },
                                   };

    FILE *fp[TARGET_NUM];

    long f_size;
    for (size_t n = 0; n < TARGET_NUM; n++) {
        fp[n] = fopen(file_names[n], "a");
        if (!fp[n]) {
            fprintf(stderr, "Error, file %s failed to open.\n", file_names[n]);
            goto cleanup;
        }
        f_size = GetFileSize(fp[n]);
        if (offset[n] < f_size) {
            fseek(fp[n], offset[n], SEEK_SET);
            fprintf(fp[n], "%s", dat[n]);
        }
    }

cleanup:
    for (size_t n = 0; n < TARGET_NUM; n++) {
        if (fp[n]) {
            fclose(fp[n]);
        }
    }
    return 0;
}

long GetFileSize(FILE *fp)
{
    fseek(fp, 0L, SEEK_END);
    long sz = ftell(fp);
    fseek(fp, 0L, SEEK_SET);
    return sz;
}

Upvotes: 0

Views: 34

Answers (1)

MikeCAT
MikeCAT

Reputation: 75062

The "a" mode means that the data will be written to end-of-file.

Try using "r+" mode (read + write) instead.

Quote from N1570 7.21.5.3 The fopen function:

6 Opening a file with append mode ('a' as the first character in the mode argument) causes all subsequent writes to the file to be forced to the then current end-of-file, regardless of intervening calls to the fseek function.

This means that file pointer opened with "a" mode will ignore operations performed with fseek.

Upvotes: 1

Related Questions