Carriage return not detected with fopen

2 views (last 30 days)
Matthieu Magnon
Matthieu Magnon on 15 May 2019
Commented: Matthieu Magnon on 16 May 2019
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:
Screenshot from 2019-05-15 11-46-22.png
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

Answers (1)

Walter Roberson
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
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)
Matthieu Magnon
Matthieu Magnon on 16 May 2019
Sorry my message was unclear: I call fopen only once, I just request an other string pattern.
To resume: altough the pattern "x_step_inv = %f\n" in present several times in the file, but the resulting commend is still empty. And for the pattern "nb_elements = %d\n", only the first occurrence is detected, not the other ones.

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!