MATLAB Solving Matlab fscanf & fgets Issue - Tips & Suggestions

  • Thread starter Thread starter justinplume
  • Start date Start date
  • Tags Tags
    Matlab
AI Thread Summary
Using fgets to count the number of lines in a file causes the file pointer to move to the end of the file, which prevents fscanf from reading any data afterward. To resolve this, it's necessary to reset the file pointer to the beginning of the file using fseek before calling fscanf. The original code had a commented-out fseek line that was not being utilized. By moving the fseek command to the appropriate location after counting the lines, the issue was fixed, allowing for successful data reading without needing to manually enter the number of lines in the file.
justinplume
Messages
2
Reaction score
0
i use fgets to get the number of lines in my file to get rid of the header, but when i do this i can't us fscanf to get the actual data, but it doesn't work any more. Tips and suggestions? Before i entered number of lines in the file. This is how it currently stands:

cldden = fopen(filename, 'r');
%fseek(cldden, 311, 'bof');
nLines = 0;
while (fgets(cldden) ~= -1),
nLines = nLines + 1;
end
length_of_data = nLines-7;
CLD_data_matrix_temp = fscanf(cldden, '%lg %lg %lg %lg %lg %lg %lg %lg %lg %lg %lg', [11,length_of_data]);
fclose(cldden);
 
Physics news on Phys.org
I don't know matlab, but because of the function naming I will assume it works the same as in C++.
After fgets'ing all the data, your handle points to the end of the file, hence fscanf doesn't read anything anymore. You will have to go back to the beginning (isn't that what the commented out line does? otherwise just close and re-open the file).
 
Thanks! i moved the fseek. I am working w/someone elses code and they had to enter the number of lines in a file and i thought that was silly and tried to update it. This worked!
 

Similar threads

Replies
1
Views
3K
Replies
18
Views
6K
Replies
3
Views
2K
Replies
4
Views
7K
Replies
1
Views
3K
Replies
4
Views
1K
Back
Top