How do you read from a file using C programing

Dani AI

Generated

Quick summary for : is right that C++ has stream classes and showed how easy it is in Python, but in plain C the standard approach uses the stdio functions. pointed you in the right direction; below are practical, safe examples and a few gotchas to avoid.

A simple, robust pattern for text files uses fopen, fgets, error checks and fclose:

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    FILE *f = fopen("input.txt", "r");
    if (!f) { perror("fopen"); return 1; }

    char buf[512];
    while (fgets(buf, sizeof buf, f) != NULL) {
        fputs(buf, stdout); /* process the line */
    }

    if (ferror(f)) perror("read error");
    fclose(f);
    return 0;
}

To read binary data (or large blocks), use fread and check its return value:

#include <stdio.h>

int main(void) {
    FILE *f = fopen("data.bin", "rb");
    if (!f) { perror("fopen"); return 1; }

    unsigned char buf[1024];
    size_t n;
    while ((n = fread(buf, 1, sizeof buf, f)) > 0) {
        /* process n bytes in buf */
    }

    if (ferror(f)) perror("read error");
    fclose(f);
    return 0;
}

Helpful tips and troubleshooting: open with "rb" on Windows for binary to avoid CRLF translation; always check fopen for NULL and use perror or errno to diagnose path/permission issues; avoid while(!feof(file)) loops; prefer fgets + sscanf over fscanf for safer parsing; use dynamic buffers or POSIX getline when lines exceed fixed buffers (note getline is POSIX, not in older C standards). If an IDE can't find the file, the working directory is usually the project/run directory — try an absolute path when debugging.

Recommended Answers

All 3 Replies

Dont know about plain C but in C++ i use th use iostream and fstream libaries and then use the ifstream and ofstream objects to manipulate the I/O streams.

commented: Such a completely useless post. -3
commented: I disagree, it is useful. +17

This is easy question to C/C++ guys if you posted at their forums.
In python it is as simple as
open("filename.extensin", "mode")
for example f = open("", "r")

fopen, then fread() or fgets() depending on what kind of file you're trying to read. Why don't you go look it up, because I don't feel like helping someone who's too lazy to even bother posting their questions in the right forum.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.