Matlab help! Need a little help!

From the image, here is my code. I'm having a little trouble creating a text file. I want the 'count' to return the number of characters successfully read but it returns '0' I don't know why... I want my text to be 'My name is Jonathan Diaz' Please help!

답변 (2개)

Steven Lord
Steven Lord 2017년 4월 25일

0 개 추천

"To read and write to the same file:
  • Open the file with a value for permission that includes a plus sign, '+'.
  • Call fseek or frewind between read and write operations. For example, do not call fread followed by fwrite, or fwrite followed by fread, unless you call fseek or frewind between them."
You probably also don't want to use fread here. The fread and fwrite functions are intended for binary data, while fprintf and fscanf are intended for text data.
AstroGuy1984
AstroGuy1984 2017년 4월 25일
편집: AstroGuy1984 2017년 4월 25일

0 개 추천

Your first invocation of fread() failed because you had closed the file first, making fid invalid. You seem to have noticed this.
Your second attempt is because of the differences of reading the file versus writing it. In addition, the position of MATLAB within the file. Notice that the following won't work either:
fid = fopen('tst.txt', 'wt');
fprintf(fid, 'Hello there Jonathan');
frewind(fid);
[~, count] = fread(fid, '*char');
fclose(fid);
You REALLY don't want to read and write a file at the same time. It's asking for trouble. Yes, you can use the '+' character but unless you are absolutely sure of where you are in a file, it's going to become a nightmare quickly. Instead, you'll want to close the file and then reopen it in READ mode... then run fread().

댓글 수: 3

Guillaume
Guillaume 2017년 4월 25일
You cannot "read" and "write" a file at the same time
Completely untrue, and does not require any trick other than telling matlab to open the file in read/write mode with the addition of the '+' suffix to the permission. However, as per the documentation you have to make sure to call fseek or frewind between read and write to make sure the respective buffers are flushed.
AstroGuy1984
AstroGuy1984 2017년 4월 25일
Yes, I noticed this mistake immediately after I posted it an edited it accordingly. Thanks anyway.
Guillaume
Guillaume 2017년 4월 25일
Ok. I still disagree with your comment "You REALLY don't want to read and write a file at the same time." in general. It is a common pattern when you want to search and replace in file. However, in this case, it would indeed make more sense to close the file and reopen it in read mode.
Note that your example that does not work can be made to work simply by changing 'wt' to 'wt+'

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

카테고리

도움말 센터File Exchange에서 Large Files and Big Data에 대해 자세히 알아보기

태그

질문:

2017년 4월 25일

댓글:

2017년 4월 25일

Community Treasure Hunt

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

Start Hunting!

Translated by