0

I want to modify this function to read files line by line into an array.

Currently this function will read the entire contents of the file into one single array index.

The function in question is "loadfile".

I am not sure where to start in-order to accomplish this.

Here is the code + the output in the terminal.

void *loadfile(char *file, int *size)
{
    FILE *fp;
    long lSize;
    char *buffer;

    fp = fopen ( file , "rb" );
    if( !fp ) perror(file),exit(1);

    fseek( fp , 0L , SEEK_END);
    lSize = ftell( fp );
    rewind( fp );

    /* allocate memory for entire content */
    buffer = calloc( 1, lSize+1 );
    if( !buffer ) fclose(fp),fputs("memory alloc fails",stderr),exit(1);

    /* copy the file into the buffer */
    if( 1!=fread( buffer , lSize, 1 , fp) )
      fclose(fp),free(buffer),fputs("entire read fails",stderr),exit(1);

    /* do your work here, buffer is a string contains the whole text */
    size = (int *)lSize;
    fclose(fp);
    return buffer;
}

int main(int argc, char* argv[]){

printf("hello\n", "%s");

int i;
char* array[6];

for(i = 0; i < 6; i++){
  array[i] = loadfile("sample_in.txt", 1);
  //printf("Content: %s", array[i]);
}


printf("ARRAY_INDEX_0: %s", array[0]);
    }

OUTPUT: (the entire contents of the file)

ARRAY_INDEX_0: pwd
ls -l -a -F
ps
pwd -L -P
ls
  • Please take a look at this post as it should answer your question already: https://stackoverflow.com/a/3747128/2016565 – Andreas Hinderberger Oct 09 '20 at 17:13
  • Why do you pass 1 to `loadfile`? It is supposed to be an `int*`. This line: `size = (int*) lSize;` changes the value of a passed argument. You probably meant to do `*size = (int) lSize;` to pass the size back to the caller. But since you pass 1 to the function, your app will crash. – Jim Rhodes Oct 09 '20 at 17:14
  • FWIW, given `fp = fopen ( file , "rb" );`, your call to `fseek( fp , 0L , SEEK_END);` is [undefined behavior in strictly-conforming C code](https://port70.net/~nsz/c/c11/n1570.html#note268): "Setting the file position indicator to end-of-file, as with `fseek(file, 0, SEEK_END)`, has undefined behavior for a binary stream ..." Using `fseek()`/`ftell()` to get the size of a file is not portable and relies on your operating system's specific implementation details, so you might as well do `struct stat sb; fstat( fileno( fp ), &sb ); long long file_size = sb.st_size;` Even Windows supports that. – Andrew Henle Oct 09 '20 at 17:15
  • Should it solve my problem? @AndreasHinderberger , that post deals with reading the whole file , new lines and all I believe – John Doe Oct 09 '20 at 20:24
  • @JimRhodes The reason I did that is because I don't exactly know how the program works, as it's something I got from the internet. – John Doe Oct 09 '20 at 20:25

0 Answers0