Carriage return not detected with fopen

4 次查看(过去 30 天)
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

回答(1 个)

Walter Roberson
Walter Roberson 2019-5-15
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 个评论
Walter Roberson
Walter Roberson 2019-5-15
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 2019-5-16
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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Low-Level File I/O 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by