C++ std::fgets
Open a small text note and read back its contents.
A simple example
std::fgets
- Start with A file containing A
- Do this Read it as text
- Result "A"
Syntax
std::fgets(note, sizeof note, file)
Run these examples in C++
Save one example at a time as lesson.cpp. Use C++17 on macOS or Linux with a POSIX shell.
c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lessonRead a saved shopping note
A small application saves a human-readable note for the next time it opens. Choose the text encoding and read or write the file deliberately so the saved characters can be recovered as intended.
#include <cstdio>
int main() {
std::FILE *file = std::tmpfile();
if (!file) return 1;
if (std::fputs("milk", file) == EOF) { std::fclose(file); return 1; }
std::rewind(file);
char note[16];
if (!std::fgets(note, sizeof note, file)) { std::fclose(file); return 1; }
std::puts(note);
std::fclose(file);
return 0;
}
milk
The buffer has space for the four letters and the string terminator. A longer line can require several reads.
Prepare a gallery label
A curator stores a short UTF-8 caption beside an exhibit. Save the note and read it back before the desk closes. Which characters are recovered?
Prepare a studio handover
A stage manager saves a two-word instruction for the next shift. Save the note and read it back before the desk closes. Which characters are recovered?
What to watch for
Use an explicit text encoding for shared data. A large file is usually better read in smaller pieces.