Results 1 to 5 of 5

Thread: Read a file into a variable

  1. #1

    Thread Starter
    Fanatic Member Geespot's Avatar
    Join Date
    Oct 2001
    Location
    Birmingham, UK
    Posts
    577

    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

  2. #2
    Frenzied Member
    Join Date
    Jul 2002
    Posts
    1,370
    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);
    }

  3. #3
    Frenzied Member Zaei's Avatar
    Join Date
    Jul 2002
    Location
    My own little world...
    Posts
    1,710
    You cannot define a char buffer of that size, because it blows your stack out of the water. It is just too big.

    Z.

  4. #4
    Frenzied Member
    Join Date
    Jul 2002
    Posts
    1,370
    Um.

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

  5. #5
    Frenzied Member Zaei's Avatar
    Join Date
    Jul 2002
    Location
    My own little world...
    Posts
    1,710
    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
  •  



Click Here to Expand Forum to Full Width