Disponible uniquement en anglais
Sysquake Pro – Table of Contents
Sysquake for LaTeX – Table of Contents
File Input/Output Functions
Access to any kind of file can be useful to analyze data which come from other applications (such as experimental data) and to generate results in a form suitable for other applications (such as source code or HTML files). Functions specific to files are described in this section. Input, output, and control are done with the following generic functions:
Function | Description |
---|---|
fclose | close the file |
feof | check end of file status |
fflush | flush I/O buffers |
fgetl | read a line |
fgets | read a line |
fprintf | write formatted data |
fread | read data |
frewind | reset the current I/O position |
fscanf | read formatted data |
fseek | change the current I/O position |
ftell | get the current I/O position |
fwrite | write data |
redirect | redirect output |
fopen
Open a file.
Syntax
fd = fopen(path) fd = fopen(path, mode)
Description
fopen opens a file for reading and/or writing. The first argument is a path whose format depends on the platform. If it is a plain file name, the file is located in the current directory; what "current" means also depends on the operating system. The output argument, a real number, is a file descriptor which can be used by many input/output functions, such as fread, fprintf, or dumpvar.
The optional second input argument, a string of one or two characters, specifies the mode. It can take one of the following values:
Mode | Meaning |
---|---|
(none) | same as 'r' |
'r' | read-only, binary mode, seek to beginning |
'w' | read/write, binary mode, create new file |
'a' | read/write, binary mode, seek to end |
'rt' | read-only, text mode, seek to beginning |
'wt' | read/write, text mode, create new file |
'at' | read/write, text mode, seek to end |
In text mode, end-of-line characters LF, CR and CRLF are all converted to LF ('\n') on input. On output, they are converted to the native sequence for the operating system, which is CRLF on Windows and LF elsewhere. To force the output end-of-line to be LF irrespectively of the operating system, use 'q' instead of 't' (e.g. 'wq' to write to a file); to force it to be CRLF, use 'T' (e.g. 'aT' to append to a file).
Examples
Reading a whole text file into a string:
fd = fopen('file.txt', 'rt'); str = fread(fd, inf, '*char'); fclose(fd);
Reading a whole text file line by line:
fd = fopen('file.txt', 'rt'); while ~feof(fd) str = fgets(fd) end fclose(fd);
Writing a matrix to a CSV (comma-separated values) text file:
M = magic(5); fd = fopen('file.txt', 'wt'); for i = 1:size(M, 1) for j = 1:size(M, 2)-1 fprintf(fd, '%g,', M(i,j)); end fprintf(fd, '%g\n', M(i,end)); end fclose(fd);
Reading 5 bytes at offset 3 in a binary file, giving an 5-by-1 array of unsigned 8-bit integers:
fd = fopen('file.bin'); fseek(fd, 3); data = fread(fd, 5, '*uint8'); fclose(fd);