- 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."
Matlab help! Need a little help!
1 view (last 30 days)
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!
Steven Lord on 25 Apr 2017
From the documentation:
"To read and write to the same file:
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 on 25 Apr 2017
Edited: AstroGuy1984 on 25 Apr 2017
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');
[~, count] = fread(fid, '*char');
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().