Salta al contenuto
Note per Studenti Files and Formatted IO Report

Files and Formatted IO

In questa pagina 12

Besides stdin and stdout, which the operating system connects automatically, a program can use other files: they must be opened before being read or written. Console basics are in Input and Output in Cconsole input and output in C through the standard library: getchar and putchar, redirection and pipes, printf and scanf format specifications, sprintf and sscanf, plus the equivalent C++ streams.Input and Output in C →; error reporting is in Standard Library Functionsstandard library functions used in the course beyond basic I/O: error handling with stderr, exit status, errno, perror and strerror, running commands with system, variadic functions with stdarg, and a map of the other library functions met in the slides.Standard Library Functions →.

File pointer and fopen

fopen takes an external file name and, after "negotiations with the operating system", returns a file pointer. It points to a structure holding the buffer location, the current position in the buffer, whether the file is read or written, and whether errors or end of file occurred. FILE is a type name defined with typedef in <stdio.h> (not a structure tag).

c
FILE *fp;
FILE *fopen(char *name, char *mode);
fp = fopen(name, mode);
Mode Meaning
"r" read; the file must exist
"w" create an empty file for writing; an existing file is erased
"a" append at the end; created if it does not exist
"r+" read and write (update); the file must exist
"w+" create an empty file for reading and writing
"a+" read and append
  • Add b to the mode for binary files on systems that distinguish text and binary.
  • Writing or appending to a missing file creates it; opening an existing file for writing discards its contents, for appending preserves them.
  • Reading a missing file, or one without permission, is an error: fopen returns NULL. Always test it.

Reading and writing

c
int getc(FILE *fp);                 // next char from fp, EOF at end of file or error
int putc(int c, FILE *fp);          // writes c, returns it (EOF on error)
int fgetc(FILE *fp);                // same as getc, always a true function
int fscanf(FILE *stream, const char *format, ...);    // formatted read
int fprintf(FILE *stream, const char *format, ...);   // formatted write
size_t fread(void *ptr, size_t size, size_t count, FILE *stream);
size_t fwrite(const void *ptr, size_t size, size_t count, FILE *stream);
  • fscanf and fprintf are scanf and printf with a file pointer as first argument.
  • fread reads count elements of size bytes into the buffer ptr; fwrite writes them out.
c
fprintf(file, "This is an integer: %d\n", 42);
int number;
fscanf(file, "This is an integer: %d", &number);
char buffer[100];
fread(buffer, sizeof(char), 100, file);
char data[] = "This is a sample text.";
fwrite(data, sizeof(char), strlen(data), file);

getc vs fgetc

getc fgetc
Implementation often a macro a true function
Speed may be slightly faster slightly slower
Thread safety may not be safe as a macro generally safer
Portability may differ between systems consistent, preferred for portable code

Line input and output: fgets and fputs

c
char *fgets(char *str, int n, FILE *fp);
int fputs(const char *str, FILE *fp);
  • fgets reads at most n-1 characters, stopping at a newline, end of file or after n-1 characters; it keeps the newline in the string if read, and always adds '\0'. Returns str on success; NULL at end of file with nothing read (contents of str unchanged) or on error.
  • fputs writes a null-terminated string; returns a non-negative value, EOF on error. Unlike puts it does not add a newline; the string must be null-terminated or it will keep reading memory.
c
char buffer[100];
while (fgets(buffer, sizeof(buffer), file) != NULL)
    printf("%s", buffer);                    // each line read from the file

if (fputs("Hello, World!\n", file) == EOF)
    perror("Error writing to file");

fgets(str, N, stdin) is also the safe way to read a line from the keyboard.

Positioning: fseek, ftell, rewind

c
int fseek(FILE *fp, long int offset, int origin);   // 0 on success, non-zero otherwise
long int ftell(FILE *fp);                           // current position, -1 on failure
void rewind(FILE *stream);                          // back to the beginning

origin is one of SEEK_SET (beginning), SEEK_CUR (current position), SEEK_END (end of file); offset is in bytes.

c
// size of a file
FILE *fp = fopen("file.txt", "r");
if (fp == NULL) { printf("Error opening file"); return(-1); }
fseek(fp, 0, SEEK_END);
int len = ftell(fp);
fclose(fp);
printf("Total size of file.txt = %d bytes\n", len);

End of file: feof

int feof(FILE *fp); returns non-zero if the end-of-file indicator is set. It does not predict the end: it is true only after a read has failed because of EOF.

  • Mistake: using feof as the loop condition. Use the return value of the read (fgetc, fgets, fscanf...) as condition, and check feof afterwards to confirm that EOF was the reason.
  • If feof is used inside the loop, test it right after the read and before using the data:
c
while (some_condition) {
    c = fgetc(fp);
    if (feof(fp)) break;
    printf("%c", c);
}

Closing, removing, renaming

c
int fclose(FILE *fp);                 // flushes buffers and closes; 0 on success, EOF otherwise
int remove(const char *filename);     // deletes the file; 0 on success
int rename(const char *old_filename, const char *new_filename);   // 0 on success
  • After fclose, any further access to the stream (even a second fclose) is undefined behavior.
  • fclose is called automatically for every open file when the program terminates normally.
  • The slides state that on failure remove and rename return -1; always test for ret == 0 for success.
c
int ret = remove(filename);
if (ret == 0) printf("File deleted successfully");
else          printf("Error: unable to delete the file");

stdin, stdout, stderr

The system opens three files at program start, with pointers stdin, stdout, stderr declared in <stdio.h>. Normally stdin is the keyboard, stdout and stderr the screen; stdin and stdout can be redirected to files or pipes, stderr still reaches the screen (see Standard Library Functionsstandard library functions used in the course beyond basic I/O: error handling with stderr, exit status, errno, perror and strerror, running commands with system, variadic functions with stdarg, and a map of the other library functions met in the slides.Standard Library Functions →).

Buffering: setvbuf and fflush

c
int setvbuf(FILE *fp, char *buffer, int mode, size_t size);   // 0 on success
  • buffer: buffer allocated by the user; if NULL the library allocates one of size bytes.
  • mode:
    • _IOFBF full buffering: output written when the buffer is full; input buffer filled when an input is requested (large files).
    • _IOLBF line buffering: output written at newline or when full; input filled up to the next newline (line-oriented text).
    • _IONBF no buffering: every operation is done as soon as possible; buffer and size are ignored.
c
char buffer[1024];
if (setvbuf(file, buffer, _IOFBF, sizeof(buffer)) != 0)
    perror("Failed to set buffer");
fputs("This is some buffered data.\n", file);
fclose(file);
c
int fflush(FILE *stream);   // forces buffered output to be written; 0 or EOF
  • Works on stdout, stderr or any file opened with fopen; with NULL it flushes all open output streams.
  • Without fflush(stdout), output may stay in the buffer until a newline is printed or the program ends.
  • On files, it makes sure data is really written before closing or going on.

The slide example sets full buffering on stdout with a 1024-byte buffer, prints two lines, calls fflush(stdout) and then prints one more line before sleep(5); the last line appears only at the end.

Temporary files

c
char *tmpnam(char *str);     // unique file NAME, does not create the file
FILE *tmpfile(void);         // creates a unique file, opened "wb+", deleted at fclose or exit
  • tmpnam: with str == NULL it uses an internal static buffer; the buffer should hold L_tmpnam characters; returns NULL on failure. The name is unique during the run, but other programs could create a file with the same name (race conditions): considered unsafe (and deprecated).
  • tmpfile is safer: automatic deletion, no name conflicts, binary read/write mode (text works too). Returns NULL on failure (permissions, space).
c
FILE *tempFile = tmpfile();
if (tempFile == NULL) { perror("Failed to create temporary file"); return 1; }
fputs("This is a temporary file.\n", tempFile);
rewind(tempFile);                        // back to the start to read what was written
char buffer[100];
while (fgets(buffer, sizeof(buffer), tempFile) != NULL)
    printf("%s", buffer);
fclose(tempFile);                        // the file is deleted here

Worked examples from the slides

Copy the keyboard into a file, then show the file (the slide listing is flawed: it includes <conio.h>, has a misplaced parenthesis in getc(fp)! = EOF, and stores the result in a char; a correct version keeps the same structure with int ch).

c
#include <stdio.h>
int main() {
    FILE *fp;
    int ch;
    fp = fopen("hello.txt", "w");
    printf("Type the data: ");
    while ((ch = getchar()) != EOF)
        putc(ch, fp);
    fclose(fp);
    fp = fopen("hello.txt", "r");
    while ((ch = getc(fp)) != EOF)
        printf("%c", ch);
    fclose(fp);
}

Greetings from a list of names (errors go to stderr, exit codes use EXIT_FAILURE / EXIT_SUCCESS):

c
#include <stdio.h>
#include <stdlib.h>
int main() {
    FILE *names = fopen("names.txt", "r");
    FILE *greet = fopen("greet.txt", "w");
    if (!names || !greet) {                       // check that all is fine
        fprintf(stderr, "Apertura del file fallita!\n");
        return EXIT_FAILURE;
    }
    char name[20];
    while (fscanf(names, "%s\n", name) > 0)       // keep reading until fscanf fails
        fprintf(greet, "Ciao, %s!\n", name);
    if (feof(names))                              // reached the end of the input
        printf("The greetings are over!\n");
    return EXIT_SUCCESS;
}

Binary I/O and best practices (summary slides)

  • Binary I/O reads and writes raw bytes (images, structured records) with fread and fwrite: they need the buffer pointer, element size, count and file pointer.
  • Error detection: feof, ferror, clearerr; message with perror.
  • Text I/O: fgetc, fputc, fgets, fputs; binary I/O: fread, fwrite.
  • Reading numbers: fscanf in a loop until EOF.
  • Copying files: fread and fwrite with a buffer.
  • Random access: fseek, ftell, rewind; secure temporary files with tmpfile() (or mkstemp()); tmpnam deprecated.
  • Always check return values; avoid raw struct dumps with fwrite for cross-platform portability.

C++ file streams

Header <fstream>: std::ifstream (read), std::ofstream (write), std::fstream (both). They work like std::cin and std::cout. Open with the constructor or .open(); read with >> (formatted) or std::getline; write with <<; call .close().

Mode flag Meaning
std::ios::in read (default for ifstream)
std::ios::out write (default for ofstream)
std::ios::app append at the end
std::ios::ate open and move the cursor to the end
std::ios::trunc truncate the file if it exists
std::ios::binary binary mode

Flags are combined with the bitwise or operator, e.g. std::ios::in with std::ios::out for a read-and-write stream.

cpp
std::ifstream inputFile("input.txt");
if (!inputFile) {                         // check that the file opened
    std::cerr << "Error opening file!" << std::endl;
    return 1;
}
std::string line;
while (std::getline(inputFile, line))     // line by line
    std::cout << line << std::endl;
inputFile.close();
cpp
int number;
while (inputFile >> number)               // read integers until failure
    std::cout << number << std::endl;

std::ofstream outputFile("output.txt");   // write
outputFile << "Hello, file!" << std::endl;

std::ofstream appendFile("output.txt", std::ios::app);   // append
  • For a read-write std::fstream, call file.clear() after reading to the end, to clear the end-of-file flag before writing.
  • Seek: .seekg() for input files, .seekp() for output files (e.g. file.seekg(10), file.seekp(0, std::ios::end)).
  • Binary: open with std::ios::binary and use .read() and .write() with a reinterpret_cast<char*> of the data:
cpp
int numbers[5] = {1, 2, 3, 4, 5};
std::ofstream outputFile("data.bin", std::ios::binary);
outputFile.write(reinterpret_cast<char*>(numbers), sizeof(numbers));
outputFile.close();
int readNumbers[5];
std::ifstream inputFile("data.bin", std::ios::binary);
inputFile.read(reinterpret_cast<char*>(readNumbers), sizeof(readNumbers));

Exercises (statements from the slides)

  1. Open a file name passed as argument and print its content to stdout.
  2. Count lines, words and characters and print Lines: X Words: Y Chars: Z.
  3. numbers.txt has integers separated by spaces or newlines: print count, sum and average.
  4. Open a file name passed in argv; if opening fails print an error message and exit with a non-zero code.
  5. Print the last 100 bytes of a file (like tail -c 100).
  6. Use a secure temporary file: write some data, rewind, read it back.

Related: Input and Output in Cconsole input and output in C through the standard library: getchar and putchar, redirection and pipes, printf and scanf format specifications, sprintf and sscanf, plus the equivalent C++ streams.Input and Output in C →, Standard Library Functionsstandard library functions used in the course beyond basic I/O: error handling with stderr, exit status, errno, perror and strerror, running commands with system, variadic functions with stdarg, and a map of the other library functions met in the slides.Standard Library Functions →, Pointers and Dynamic Memorypointers in C: address and dereference operators, pointer arguments, pointers to functions, and dynamic memory allocation with malloc, calloc, realloc and free, with the checks and exercises given in the course.Pointers and Dynamic Memory →.

Versione ripasso

  • fopen(name, mode) returns a FILE * or NULL: always test for NULL. Modes: "r" (must exist), "w" (creates or erases), "a" (append, creates), "r+" (read and write, must exist), "w+" (create, read and write), "a+" (read and append). Add b for binary on systems that distinguish it.
c
FILE *fp = fopen("names.txt", "r");
if (fp == NULL) { perror("fopen"); return EXIT_FAILURE; }
  • Character I/O: getc / fgetc (macro versus true function; fgetc preferred for portable code), putc(c, fp). Formatted: fscanf(fp, ...), fprintf(fp, ...), the same as scanf and printf with a file first. Blocks: fread(buf, size, count, fp) and fwrite(buf, size, count, fp).
  • fgets(str, n, fp): reads at most n-1 chars, stops at \n or EOF, keeps the \n, always adds '\0', returns NULL at EOF or on error. fputs(str, fp) writes a string and adds no newline.
  • Positioning: fseek(fp, offset, SEEK_SET | SEEK_CUR | SEEK_END) with the offset in bytes, ftell(fp) gives the position, rewind(fp) goes back to the start. File size: fseek(fp, 0, SEEK_END), then ftell(fp), then fclose.
  • feof(fp) is true only after a read has already failed: loop on the read's return value (fgets(...) != NULL, fscanf(...) > 0, (c = fgetc(fp)) != EOF) and use feof afterwards to find out why the loop stopped. If it is used inside the loop, test it right after the read and before using the data.
  • fclose(fp) flushes buffers and closes; any later use of the stream is undefined behavior. remove(name) and rename(old, new) return 0 on success, so test ret == 0.
  • stdin, stdout, stderr are opened by the system. Stderr stays on the screen even when stdout is redirected. Error messages go to stderr: fprintf(stderr, ...).
  • Buffering: setvbuf(fp, buf, mode, size) with _IOFBF (full), _IOLBF (per line), _IONBF (none). fflush(fp) forces the buffered output out; without it, stdout may wait for a newline or for the program to end. fflush(NULL) flushes every output stream.
  • Temporary files: tmpfile() creates a file opened "wb+" that is deleted at fclose or at exit, so it is safe. tmpnam only gives a name, which another program can take (race conditions), so it is unsafe and deprecated. Rewind before reading back what was written.
  • Worked example, copy keyboard to file and show it: read with while ((ch = getchar()) != EOF) putc(ch, fp);, close, reopen with "r", read back with getc. Use int ch, not char, to compare with EOF.
  • Greetings example: while (fscanf(names, "%s\n", name) > 0) fprintf(greet, "Ciao, %s!\n", name); then if (feof(names)) confirms the end of the input.
  • Binary data: fread and fwrite move raw bytes. Avoid dumping whole structs with fwrite across platforms, because padding and byte order change.
  • C++ streams (<fstream>): std::ifstream (read), std::ofstream (write), std::fstream (both). Check the stream with if (!inputFile). Read with while (std::getline(inputFile, line)) or while (inputFile >> number); write with <<; append with std::ios::app; binary with std::ios::binary and .read() / .write() through reinterpret_cast<char*>.
  • In a read-write std::fstream, call file.clear() after reaching the end, to clear the EOF flag before writing. .seekg() moves the input position, .seekp() the output one.
  • Typical errors: not testing fopen, feof as the loop condition, opening with "w" by mistake (it erases the file), forgetting fclose, fgets keeping the \n, using char instead of int for getchar results, using a file pointer after fclose.

Related: Input and Output in Cconsole input and output in C through the standard library: getchar and putchar, redirection and pipes, printf and scanf format specifications, sprintf and sscanf, plus the equivalent C++ streams.Input and Output in C →, Standard Library Functionsstandard library functions used in the course beyond basic I/O: error handling with stderr, exit status, errno, perror and strerror, running commands with system, variadic functions with stdarg, and a map of the other library functions met in the slides.Standard Library Functions →, Pointers and Dynamic Memorypointers in C: address and dereference operators, pointer arguments, pointers to functions, and dynamic memory allocation with malloc, calloc, realloc and free, with the checks and exercises given in the course.Pointers and Dynamic Memory →.

Teoria collegata