필터 지우기
필터 지우기

Error in Reading and Writing a text file

조회 수: 1 (최근 30일)
X
X 2011년 7월 11일
I have a problem with my program when i read and write the file. The following code is what I have so far. It works when I use only textscan and fopen with 'r' instead of 'r+'. The error is Invalid file identifier, Use fopen to generate a valid file identifier. Can somebody see a mistake? Thank you in advance
fid = fopen('3.csv', 'r+'); %Opens the file
NData = textscan(fid, '%s %s %d % ... %d', 'delimiter' ,',', 'headerlines',2);
T_DB = NData {32}; %Gets Dry Bullb Temperature
T_DP = NData {35}; %Gets Dew Point Temperature
RH = NData {38}; %Gets Relative Humitidy
Temp_data = [T_DB T_DP RH];
frewind(fid)
fprintf(fid, '%f %f %f', Temp_data);
fclose(fid); %Closes the file

채택된 답변

Jan
Jan 2011년 7월 11일
While "fopen(FileName, 'r')" searchs the file in all folders of the Matlab path, "fopen(FileName, 'r+')" looks in the current folder only. To solve this, change into the folder, which contains the file (see CD) or specify the file by a full path (see FULLFILE).
As a side-effect the fopen with 'r+' is about 2.3 times faster than with 'r' even if the file is specified with a full path.
  댓글 수: 1
Fangjun Jiang
Fangjun Jiang 2011년 7월 11일
This could be the reason! Now I notice this sentence in help fopen. "FILENAME can be a MATLABPATH relative partial pathname only if the file
is opened for reading."

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Fangjun Jiang
Fangjun Jiang 2011년 7월 11일
Since you are reading and writing the same file, it is surprise to hear that 'r' (read only) works but 'r+' (read and write but not to create new) doesn't. Are you sure it is not the opposite?
Since you are read and write text file, I wonder if 'r+t' would help.
  댓글 수: 5
Fangjun Jiang
Fangjun Jiang 2011년 7월 11일
All right, good to know! The example provided in help fopen shows 'w+t'
Jan
Jan 2011년 7월 11일
@Jiang: Walter's link contains a 'wt+' example also.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Low-Level File I/O에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by