skippy_winks
skippy_winks

Reputation: 778

How to read multiple .txt files into a single buffer?

I am trying to read multiple text files into a single char* array in C. I can get as far as allocating the char* to the correct size (i.e. the sizes of all the text files summed up).

I tried to read each file, one by one, into their own buffer, then concatenate that buffer onto the end of the one that contains them all. This is all done in a for-loop. But when I print it out to make sure it worked, only the last file that was read is printed out.

I have also tried fread, but that seems to overwrite the buffer that it writes to, rather than append to the end of it.

Here is my code, most of it is from another SO thread:

for(int i = 2; i < argc; i++) {
char *buffer = NULL;
size_t size = 0;

/* Get the buffer size */
fseek(file, 0, SEEK_END); /* Go to end of file */
size = ftell(file); /* How many bytes did we pass ? */
/* Set position of stream to the beginning */
rewind(file);
/* Allocate the buffer (no need to initialize it with calloc) */
buffer = malloc((size + 1) * sizeof(*buffer)); /* size + 1 byte for the \0 */
/* Read the file into the buffer */
fread(buffer, size, 1, file); /* Read 1 chunk of size bytes from fp into buffer */
/* NULL-terminate the buffer */
buffer[size] = '\0';

allFiles = strcat(allFiles, buffer);
free(buffer);
fclose(file);
}

Please help me out, I am stumped by what seems like a simple thing to do in C. Thanks.

Upvotes: 0

Views: 1120

Answers (1)

UziMonkey
UziMonkey

Reputation: 136

It sounds like you're doing everything correct, but you need to increment the pointer before you pass it to fread for the next file otherwise you'll overwrite the beginning of the file over and over.

Assuming buf is the correct size for all the files +1 for the nul byte and files is an array of char *'s containing the filenames NUM_FILES long, you'll need to do something like this.

char *p = buf;
for(int i = 0; i < NUM_FILES; i++) {
    FILE *f = fopen(files[i], "rb");

    fseek(f, 0, SEEK_END);
    long bytes = ftell(f);
    fseek(f, 0, SEEK_SET);

    fread(p, (size_t)bytes, 1, f);
    p += bytes;

    fclose(f);
}
*p = 0;

Upvotes: 2

Related Questions