Quick Question: Is there a way in c to read an entire file into a string or char buffer?
Thanks, Elise
Jump to PostExcept 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
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]
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
thanks y'all, that was a big help.
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.
You're trying to visit a URL that doesn't currently exist on the web. Most likely, a member posted a link a long time ago to a web page that has since been removed. It's also possible that there was a typo when posting the URL. We redirect you to this notice instead of stripping out the link to preserve the integrity of the post.