13.4k views
4 votes
When a file has been opened using the 'r' mode specifier, which method will return the file's contents as a string??

User Arku
by
8.6k points

1 Answer

6 votes
Assuming we're talking C here:

I would opt for fread() with the following notes:
- there are no guarantees that the whole file counts as one string.
- you need to know the length of the file to allocate enough memory.
- you need to append a trailing 0 in memory to terminate the string.

fgets() does return a 0-terminated string but is not exactly what is asked since it only reads until the next newline character which may be in the middle of the file.
User Slattery
by
8.0k points