PDA

Click to See Complete Forum and Search --> : Read a file into a variable


Geespot
Sep 1st, 2002, 10:22 AM
Hi

How can i read an entire file into a variable?


pfile2 = fopen("filename.txt", "r");

long counter=0;
char sFileCheck[25000000];

while ( (mychar = fgetc(pfile2) ) != EOF )
{
sFileCheck[counter] = mychar;
counter++;
}


fclose(pfile2);

thats what i used but it crashes on the char sFileCheck[25000000)

and i cant load the file up bit by bit because i need to do something with the whole file

Thanks

jim mcnamara
Sep 1st, 2002, 12:10 PM
#include <stdio.h>
#include <sys\stat.h>
#include <stdlib.h>
void test(FILE *);
int main(int argc, char *argv[]){
FILE *in;
int i;
char *buf;
struct stat a;
if(stat(argv[1],&a)){ /* get file info, -1 = error */
perror("Cannot stat input file");
exit(EXIT_FAILURE);
}
buf=(char*)malloc(a.st_size); /* buffer size = file size */
if (fread(buf,a.st_size,1,in)){ /* we read the buffer*/
; /* do stuff */
}
fclose(in);
free(buf);
}
void test(FILE*tst){
if(tst==NULL){
perror("Error opening iput file");
exit(EXIT_FAILURE);
}

Zaei
Sep 1st, 2002, 12:15 PM
You cannot define a char buffer of that size, because it blows your stack out of the water. It is just too big.

Z.

jim mcnamara
Sep 1st, 2002, 08:24 PM
Um.

You can malloc() a buffer of almost any size (memory + ~swapfile space)- the wait may not be practical, nut you can do it.

Zaei
Sep 1st, 2002, 09:25 PM
No, I was explaining why the original code snippet wouldnt work =).

Z.