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

Thanks, Elise

Recommended Answers

All 3 Replies

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]

thanks y'all, that was a big help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.