|
-
Sep 1st, 2002, 10:22 AM
#1
Thread Starter
Fanatic Member
Read a file into a variable
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
-
Sep 1st, 2002, 12:10 PM
#2
Frenzied Member
Code:
#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);
}
-
Sep 1st, 2002, 12:15 PM
#3
Frenzied Member
You cannot define a char buffer of that size, because it blows your stack out of the water. It is just too big.
Z.
-
Sep 1st, 2002, 08:24 PM
#4
Frenzied Member
Um.
You can malloc() a buffer of almost any size (memory + ~swapfile space)- the wait may not be practical, nut you can do it.
-
Sep 1st, 2002, 09:25 PM
#5
Frenzied Member
No, I was explaining why the original code snippet wouldnt work =).
Z.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|