Copy text file into char* array

Midge_Mong Source
FILE *fp;
char *f_array[256];
int f_length;
int *a = 0;

fp = fopen("test.txt", "r");
fseek(fp, 0, SEEK_END);
f_length = ftell(fp);
printf("%d\n\n", f_length);
int n = 1, i = 0;
while (n > 0)
    n = fscanf(fp, "%s", f_array[i]);

I am trying to copy the contents of a .txt file into a char* array. Much like what would happen with InternetReadFile and lpbuffer. However, I cannot seem to get this right. I need my array to be filled with the contents of the .txt file character by character. Any suggestions? I need the array to be single-dimensional



answered 8 months ago Pablo #1

You are calculating the length of the file but you don't use this information in any way.

char *f_array[256];

This is an array of dimension 256 of pointers to char. f_array[i] is uninitialized and it's pointing into the digital nirvana, passing it to fscanf yields undefined behaviour. You would need to declare it as something like this:

char f_array[255][255];

But then you are limiting yourself to max 255 strings, you are not storing it into a single string. Also you are storing max. 255 words. Use fgets or fread to get the whole content at once.

char file[f_length + 1];


fread(file, f_length, 1, fp);

file[f_length] = 0; // terminate the string

printf("Whole file is: %s\n", file);

Here you are storing the whole file in an array of chars. Also after setting the file at the end, you'll need to rewind the file to the beginning, otherwise you are not reading anything.

answered 8 months ago hunteke #2

The issue is mainly to do with your data types. You want to store the file in memory. That would be a character (byte) array, but you have created an "array of pointers":

char *f_array[256];

When you probably wanted just:

char f_array[256];

Then, to do as you asked and read character by character into that array, use fgetc. Note that fgetc will be far less efficient that just reading the whole file in a single function call with fread. The kernel:

while ( EOF != (c = fgetc( fp )) && ++i < MAX_LEN )
    f_array[ i ] = c;

In context of a working example:

#include <stdio.h>
int main ( ) {
    const size_t MAX_LEN = 255;
    FILE * fp;
    char f_array[ MAX_LEN +1];
    int c;
    size_t i = -1;
    f_array[ MAX_LEN +1] = 0;

    fp = fopen("test.txt","r");

    if ( NULL == fp )
        perror("Error opening file");
    else {
        while ( EOF != (c = fgetc( fp )) && ++i < MAX_LEN )
            f_array[ i ] = c;

        fclose (fp);
    f_array[ i ] = 0;
    printf("%zu bytes read\n\n", i);
    printf("Content read:\n%s\n", f_array);

    return 0;

comments powered by Disqus