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