Carriage return not detected with fopen
2 views (last 30 days)
Show older comments
Hi all,
I want to parse information in a text file, the file as the following structure:
nb_elements = 715
x_step_inv = 572.9578
-0.6170 -0.0440
-0.6160 -0.0770
[other rows...]
nb_elements = 123
x_step_inv = 572.9578
-0.6170 -0.0440
-0.6160 -0.0770
[other rows...]
nb_elements = 456
x_step_inv = 572.9578
-0.6170 -0.0440
-0.6160 -0.0770
[other rows...]
Each new line is ended by "\n" when writted in a c file. For example all 'nb_elements' lines are:
fprintf(fp, "nb_elements = %d\n", nb_elements); /* c file code */
When opened with vim, the result is:
On Matlab is use the following code:
fileID = fopen(file_path, 'wt');
A = fscanf(fileID, 'nb_elements = %d\n');
fclose(fileID):
But A is empty, it should at least returns the first nb_element value equal to 100
I have also tried below commands wtihout success:
A = fscanf(fileID, 'nb_elements = %d\r\n');
A = fscanf(fileID, 'nb_elements = %d\r');
I don't know why fscanf don't parse specified format data, any idea is welcome (I use Matlab on a Linux machine)
Matt
0 Comments
Answers (1)
Walter Roberson
on 15 May 2019
Opening a file with 'wt' tells matlab to erase the content of the file and prepare to write it with cr nl termination. You need 'r' or 'rt' for reading.
3 Comments
Walter Roberson
on 15 May 2019
fopen only once. That positions at the beginning of the file when you ask for read permission. Each fgets or fgetl or fread moves forward from the last position unless a fseek is used (or some circumstances involving having opened with different permissions)
See Also
Categories
Find more on Low-Level File I/O in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!