简体   繁体   中英

Reading text files using matlab

I'm having a rather odd problem. Reading a float from a text file as usual, the test file contains nothing but a single float:

fid = fopen('file.txt','r');
a = fscanf(fid,'%f');
fclose(fid);

If I omit the fclose... line, and then run fscanf... again, I get an empty array, because I've already scanned the entire contents of the file; this is normal behaviour.

The analysis I'm using matlab to do requires four parallel processes (which necessarily are independent and cannot pass data between each other) to each be able to read the file. The analysis takes of the order of hours and the four processes are unlikely to ever want to read the same file within half an hour of each other, it should be no issue for one process to read it and close it well before any of the other processes try to read it. My parallelisation is very simple - the four tasks are manually started from within a matlab GUI.

However, what actually happens is that the first process to try to read the file does so fine, and the others then fail, returning empty arrays as if the file hadn't been closed properly. I've dedicated hours to the problem and got nowhere, any ideas?

EDIT: if I write the file using matlab's fprintf... command, it behaves fine. It's just files printed using the c++ ofstream library that seem to be causing issues. The c++ code involved in the writing of the file is as follows:

#include <iostream>
std::ofstream param_file ( "file.txt" );
param_file<<dataval;

I've not chased down the cause of it (matlab bug maybe?), but I've got a workaround:

try
    fid = fopen('file_2.txt','r');
    a = fscanf(fid,'%f');
    fclose(fid);
    delete('file_2.txt');
    fid2 = fopen('file_2.txt','w');
    fprintf(fid2,'%f',a);
    fclose(fid2);
catch
    fid = fopen('file.txt','r');
    a = fscanf(fid,'%f');
    fclose(fid);
    fid2 = fopen('file_2.txt','w');
    fprintf(fid2,'%f',a);
    fclose(fid2);
end

This code will try and read a new file (not the original). If successful, it means the thread in question got there first, and so will then read the original file and make a new file with a different name. Subsequent threads will succeed in reading the new file, and will reset it after reading (by deleting and re-writing it) in order to facilitate subsequent threads reading the same file. It's clunky, but doesn't slow the program down in any meaningful way, and it works!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM