Solving Matlab fscanf & fgets Issue - Tips & Suggestions

  • Context: MATLAB 
  • Thread starter Thread starter justinplume
  • Start date Start date
  • Tags Tags
    Matlab
Click For Summary
SUMMARY

The discussion focuses on resolving an issue with using MATLAB's fgets and fscanf functions for reading data from a file. The user initially faced a problem where fscanf failed to read data after using fgets to count lines. The solution involved repositioning the file pointer using fseek to the beginning of the file after reading with fgets. This adjustment allowed fscanf to function correctly, enabling the user to read the desired data matrix.

PREREQUISITES
  • Understanding of MATLAB file I/O functions, specifically fgets and fscanf
  • Knowledge of file pointer manipulation using fseek
  • Familiarity with matrix data structures in MATLAB
  • Basic programming concepts related to loops and conditionals
NEXT STEPS
  • Explore MATLAB file I/O documentation to deepen understanding of fgets and fscanf
  • Learn about error handling in MATLAB file operations
  • Investigate alternative methods for reading structured data in MATLAB, such as readtable
  • Study best practices for managing file pointers in programming languages like C and MATLAB
USEFUL FOR

MATLAB programmers, data analysts, and researchers working with file data input and output, particularly those dealing with structured data formats.

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 ·
Replies
1
Views
3K
  • · Replies 18 ·
Replies
18
Views
6K
Replies
1
Views
5K
  • · Replies 4 ·
Replies
4
Views
9K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 4 ·
Replies
4
Views
7K
  • · Replies 2 ·
Replies
2
Views
6K
Replies
1
Views
2K
  • · Replies 3 ·
Replies
3
Views
5K
  • · Replies 1 ·
Replies
1
Views
4K