954,505 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

C file stream

Quick Question: Is there a way in c to read an entire file into a string or char buffer?

Thanks, Elise

rwagnes
Light Poster
36 posts since Dec 2006
Reputation Points: 10
Solved Threads: 0
 
Quick Question: Is there a way in c to read an entire file into a string or char buffer? Thanks, Elise


Yes. With fopen, SEEK_END and ftell you can determine the size of file and after SEEK_SET read the the whole file with fread.
[EDIT]

#include <stdio.h>
#include <stdlib.h>

int main()
{
   char * buff = NULL;
   int fLength = 0;
   FILE * file = NULL;

   if ((file = fopen("doc.txt", "r")) == NULL)
   {
      printf("No file \n");
      return 1;
   }
   
   fseek(file, 0, SEEK_END);
   fLength = ftell(file);
   if ((buff = malloc(fLength * sizeof(char) + 1)) == NULL)
   {
      fclose(file);
      return 1;
   }
   fseek(file, SEEK_SET, 0);
   fread(buff, sizeof(char), fLength, file);
   buff[fLength + 1] = '\0';
   puts(buff);
   free(buff);
   fclose(file);
   return 0;
}

[/EDIT]

andor
Posting Whiz in Training
276 posts since Jun 2005
Reputation Points: 251
Solved Threads: 29
 

Except simply seeking to the end doesn't take into account any translations which may occur when the file is read byte by byte (even if you do read them all in one call).
http://c-faq.com/osdep/filesize.html

Salem
Posting Sage
Team Colleague
11,531 posts since Dec 2005
Reputation Points: 5,862
Solved Threads: 953
 

thanks y'all, that was a big help.

rwagnes
Light Poster
36 posts since Dec 2006
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You