•
•
•
•
What is DaniWeb IT Discussion Community?
You're currently browsing the C section within the Software Development category of DaniWeb, a massive community of 401,946 software developers, web developers, Internet marketers, and tech gurus who are all enthusiastic about making contacts, networking, and learning from each other. In fact, there are 3,344 IT professionals currently interacting right now! Registration is free, only takes a minute and lets you enjoy all of the interactive features of the site.
Views: 1502 | Replies: 3 | Solved
![]() |
•
•
Join Date: Jun 2005
Location: Novi Sad, Serbia
Posts: 273
Reputation:
Rep Power: 6
Solved Threads: 29
•
•
•
•
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]
c Syntax (Toggle Plain Text)
#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; }
Last edited by andor : Feb 9th, 2007 at 4:16 am.
If you want to win, you must not loose (Alan Ford)
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
http://c-faq.com/osdep/filesize.html
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
Do not PM me for help; You'll be ignored, or told to learn to read.
Do not ask me if I'm muslim - I'm not. Nor do I care about yours or anyone else's mysticism. Religion is a matrix, take the RED PILL.
Do not PM me for help; You'll be ignored, or told to learn to read.
Do not ask me if I'm muslim - I'm not. Nor do I care about yours or anyone else's mysticism. Religion is a matrix, take the RED PILL.
![]() |
•
•
•
•
•
•
•
•
DaniWeb C Marketplace
•
•
•
•
Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
Similar Threads
- Making a log file global (C++)
- Need Help in Reading characters from a text file (C++)
- Getting all data from an input and output file (C++)
- ofstream - detect if file has been deleted between open and close (C++)
- A question about file streaming (C++)
- inputing system("date /t") and system("time /t") into a file (C++)
- file pointer increament (C)
- Saving a file using C++ (C++)
Other Threads in the C Forum
- Previous Thread: My own read function
- Next Thread: Simple Problem give me solution



Linear Mode