Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Matlab fscanf and fgets

  1. Jul 7, 2009 #1
    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;
    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]);
  2. jcsd
  3. Jul 7, 2009 #2


    User Avatar
    Science Advisor
    Homework Helper

    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).
  4. Jul 9, 2009 #3
    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!
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook