std::fgetc,std::getc(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

Hey bestie πŸ’– β€” this is the std::fgetc, std::getc page, section 3, from the C++ Standard Libary manual. It's giving β€œread one character from a stream” energy, and honestly? Iconic.

πŸ’– NAME πŸ’–

std::fgetc,std::getc β€” literally std::fgetc,std::getc, bestie. Periodt.

🌸 Synopsis 🌸

Defined in header <cstdio>

int fgetc( std::FILE* stream );
int getc( std::FILE* stream );

Reads the next character from the given input stream. Lowkey simple, highkey useful.

πŸŽ€ Parameters πŸŽ€

  • stream β€” the stream you're reading the character from, bestie.

πŸ’… Return value πŸ’…

The obtained character on success, or EOF on failure. No cap.

If the failure has been caused by end of file condition, it additionally sets the eof indicator (see std::feof()) on stream. If the failure has been caused by some other error, it sets the error indicator (see std::ferror()) on stream. Important vibes: those indicators are doing the emotional labor here.

✨ Example ✨

// Run this code β€” yes bestie, go off:

#include <cstdio>
#include <cstdlib>

int main()
{
    int is_ok = EXIT_FAILURE;
    FILE* fp = std::fopen("/tmp/test.txt", "w+");
    if (!fp)
    {
        std::perror("File opening failed");
        return is_ok;
    }

    int c; // Note: int, not char, required to handle EOF
    while ((c = std::fgetc(fp)) != EOF) // Standard C I/O file reading
       loop
        std::putchar(c);

    if (std::ferror(fp))
        std::puts("I/O error when reading");
    else if (std::feof(fp))
    {
        std::puts("End of file reached successfully");
        is_ok = EXIT_SUCCESS;
    }

    std::fclose(fp);
    return is_ok;
}

πŸ–₯️ Output πŸ–₯️

End of file reached successfully

πŸ‘€ See also πŸ‘€

  • gets β€” reads a character string from stdin (deprecated in C++11) (function) (removed in C++14)
  • fputc β€” writes a character to a file stream
  • putc β€” (function)
  • ungetc β€” puts a character back into a file stream (function)
  • C documentation for fgetc, getc

source: http://cppreference.com Β· version/date: 2024.06.10 Β· page: std::fgetc,std::getc(3) β€” slay and goodbye πŸ’…βœ¨

πŸ“¦ where this page comes from