how to solve the fopen error?
Show older comments
Hi all,
I've done the below code to read .txt files and extracting columns from each one. the error appears just from the second to the rest of files. Could anyone help me with this?
thank you
Error using fgets
Invalid file identifier. Use fopen to generate a valid file identifier.
Error in RUV_readFile (line 21)
line = fgets(file1);
clc
clear all
close all
%read file line by line
%loop over the files from list
%open each file and loop over the lines,
files_str = fileread('foldername/files.txt');
list = splitlines(files_str);
for k=1:length(list)
filename = list{k}; %index cell array of filenames using k
disp(filename);
file1 = fopen(strcat('foldername',filename));
filemat = [];
line = fgets(file1);
while ischar(line)
if isempty(strfind(line,'%')) %if line doesn't contains %
vec = str2num(line); %convert line string to vector
filemat = [filemat;vec]; %fill matric from vectors in file
end
% disp(line)
line = fgets(file1);
end
fclose(file1);
cols = filemat(:,1:4);
save(strcat('output/',filename), 'cols', '-ascii')
end
3 Comments
Guillaume
on 17 Aug 2017
As commented by Stephen, you're using a very inefficient way to read what appear to be a text file of numbers. textscan or even easier readtable could read it all in one go.
In addition,
- use fullfile instead of strcat to build path names. It's a lot more reliable
- Do you really have a folder called foldername? It's very unusual and I suspect the original intent of the code was to have an arbitrary folder whose name would be stored in a variable called foldername. In which case, the variable name should not be enclosed in quotes
file_str = fileread(fullfile(foldername, 'files.txt')); %NOT 'foldername'
is the usual pattern.
- similarly, are the text files you're trying all named foldernamesomething. Because that's exactly what you're trying to open. Normal code would be:
file1 = fopen(fullfile(foldername, filename)); %NOT 'foldername', filename
@Guillaume: thank you for the detailed explanation. It was remiss of me to not explain as much as you did.
@Lina Eyouni: you should read the MATLAB documentation, which shows just how simple this should be:
Lilya
on 17 Aug 2017
Accepted Answer
More Answers (0)
Categories
Find more on Dates and Time in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!