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).
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
bto 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:
fopenreturnsNULL. Always test it.
Reading and writing
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);fscanfandfprintfarescanfandprintfwith a file pointer as first argument.freadreadscountelements ofsizebytes into the bufferptr;fwritewrites them out.
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
char *fgets(char *str, int n, FILE *fp);
int fputs(const char *str, FILE *fp);fgetsreads at mostn-1characters, stopping at a newline, end of file or aftern-1characters; it keeps the newline in the string if read, and always adds'\0'. Returnsstron success;NULLat end of file with nothing read (contents ofstrunchanged) or on error.fputswrites a null-terminated string; returns a non-negative value,EOFon error. Unlikeputsit does not add a newline; the string must be null-terminated or it will keep reading memory.
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
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 beginningorigin is one of SEEK_SET (beginning), SEEK_CUR (current position), SEEK_END (end of file); offset is in bytes.
// 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
feofas the loop condition. Use the return value of the read (fgetc,fgets,fscanf...) as condition, and checkfeofafterwards to confirm that EOF was the reason. - If
feofis used inside the loop, test it right after the read and before using the data:
while (some_condition) {
c = fgetc(fp);
if (feof(fp)) break;
printf("%c", c);
}Closing, removing, renaming
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 secondfclose) is undefined behavior. fcloseis called automatically for every open file when the program terminates normally.- The slides state that on failure
removeandrenamereturn -1; always test forret == 0for success.
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
int setvbuf(FILE *fp, char *buffer, int mode, size_t size); // 0 on successbuffer: buffer allocated by the user; ifNULLthe library allocates one ofsizebytes.mode:_IOFBFfull buffering: output written when the buffer is full; input buffer filled when an input is requested (large files)._IOLBFline buffering: output written at newline or when full; input filled up to the next newline (line-oriented text)._IONBFno buffering: every operation is done as soon as possible;bufferandsizeare ignored.
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);int fflush(FILE *stream); // forces buffered output to be written; 0 or EOF- Works on stdout, stderr or any file opened with
fopen; withNULLit 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
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 exittmpnam: withstr == NULLit uses an internal static buffer; the buffer should holdL_tmpnamcharacters; returnsNULLon 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).tmpfileis safer: automatic deletion, no name conflicts, binary read/write mode (text works too). ReturnsNULLon failure (permissions, space).
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 hereWorked 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).
#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):
#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
freadandfwrite: they need the buffer pointer, element size, count and file pointer. - Error detection:
feof,ferror,clearerr; message withperror. - Text I/O:
fgetc,fputc,fgets,fputs; binary I/O:fread,fwrite. - Reading numbers:
fscanfin a loop until EOF. - Copying files:
freadandfwritewith a buffer. - Random access:
fseek,ftell,rewind; secure temporary files withtmpfile()(ormkstemp());tmpnamdeprecated. - Always check return values; avoid raw struct dumps with
fwritefor 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.
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();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, callfile.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::binaryand use.read()and.write()with areinterpret_cast<char*>of the data:
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)
- Open a file name passed as argument and print its content to stdout.
- Count lines, words and characters and print
Lines: X Words: Y Chars: Z. numbers.txthas integers separated by spaces or newlines: print count, sum and average.- Open a file name passed in
argv; if opening fails print an error message and exit with a non-zero code. - Print the last 100 bytes of a file (like
tail -c 100). - 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 aFILE *orNULL: always test forNULL. 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). Addbfor binary on systems that distinguish it.
FILE *fp = fopen("names.txt", "r");
if (fp == NULL) { perror("fopen"); return EXIT_FAILURE; }- Character I/O:
getc/fgetc(macro versus true function;fgetcpreferred for portable code),putc(c, fp). Formatted:fscanf(fp, ...),fprintf(fp, ...), the same asscanfandprintfwith a file first. Blocks:fread(buf, size, count, fp)andfwrite(buf, size, count, fp). fgets(str, n, fp): reads at mostn-1chars, stops at\nor EOF, keeps the\n, always adds'\0', returnsNULLat 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), thenftell(fp), thenfclose. 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 usefeofafterwards 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)andrename(old, new)return 0 on success, so testret == 0.stdin,stdout,stderrare opened by the system. Stderr stays on the screen even when stdout is redirected. Error messages go tostderr: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 atfcloseor at exit, so it is safe.tmpnamonly 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 withgetc. Useint ch, notchar, to compare withEOF. - Greetings example:
while (fscanf(names, "%s\n", name) > 0) fprintf(greet, "Ciao, %s!\n", name);thenif (feof(names))confirms the end of the input. - Binary data:
freadandfwritemove raw bytes. Avoid dumping whole structs withfwriteacross platforms, because padding and byte order change. - C++ streams (
<fstream>):std::ifstream(read),std::ofstream(write),std::fstream(both). Check the stream withif (!inputFile). Read withwhile (std::getline(inputFile, line))orwhile (inputFile >> number); write with<<; append withstd::ios::app; binary withstd::ios::binaryand.read()/.write()throughreinterpret_cast<char*>. - In a read-write
std::fstream, callfile.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,feofas the loop condition, opening with"w"by mistake (it erases the file), forgettingfclose,fgetskeeping the\n, usingcharinstead ofintforgetcharresults, using a file pointer afterfclose.
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 →.