overwrite a text file with other data

Ok so here is what im stuck on.
I have a text file called testdata.txt from wordpad. this file contains the data:
2 4 9 5
3 7 8 1
now i need to overwrite this file with the vector [3 6 9].
so now when i open the file testdata.txt from wordpad the data that shows should only be 3 6 9

Réponses (2)

Geoff
Geoff le 15 Mar 2012
Let's say your value is in the variable called v:
v = [3 6 9];
You can use save which will output lots of extra decimal places:
save('testdata.txt', 'v', '-ascii');
Or use file I/O (this example assumes your vector is integer):
fileID = fopen('testdata.txt', 'w');
fprintf(fileID, '%d %d %d\n', v);
fclose(fileID);

4 commentaires

lowcalorie
lowcalorie le 15 Mar 2012
ok but when i use
fopen('testdata.txt', 'w');
my file identifier does not equal -1 if testdata.txt does not exist. see because if the file does not exist the file
ID will = -1 and then i have to re-ask the user to input a file that does exist.
another problem is that it also erases everything in my file which is not good because before i overwrite the file i need to do calculations on the data in the file and i cannot do this since this statement erases my data
lowcalorie
lowcalorie le 15 Mar 2012
also my new data is always this stuff and not my 3 values
MATLAB 5.0 MAT-file, Platform: PCWIN, Created on: Thu Mar 15 00:13:02 2012 IM & xœãc``0 b6 æ€Ò À
å3Â13Cb^1% ä „¾ 6 xœãc``ð b6 æ b`…ò˜JƒÔdæ¥eæ¤20@Å3RsròõJ*J ú š§¹ $ xœãc``0 b6 æ€Ò À
å3Â1#CfÒ@ 8 ï - xœãc``° b6 æ€Ò À
å3133IŸÌ<0¤†Ý‘ ( /ðý ) xœãc``0 b6 æ€Ò À
å313˜faÈÍÌ3dòØ™ "yì % xœãc``0 b6 æ€Ò À
å3Â1 Cnfžâ "3á ) xœãc``0 b6 æ€Ò À
å313˜faÈM¬0dòØý˜ #r= & xœãc``0 b6 æ€Ò À
å3Â1 Cnb…åä #s0 # xœãc``0 b6 æ€Ò À
å3Â1#CfÒ 5 ˜ Û . xœãc``p b6 æ€Ò À
å3"av N,K-JLOeà„ʯ^Z owS 7 xœãc``ð b6 æ b`…ò˜J³q~iIZfN*ƒ T<#5''_¯¤¢ª ¨\; $ xœãc``0 b6 æ€Ò À
å3Â1#C%fÒb@ \ ö , xœãc``° b6 æ b`…ò‘0HMb^qyjƒ P$È ;ÿ 6 xœãc``ð b6 æ€Ò À
å313˜fd(Òœ@,Ä«W–Dõ{0Õì ™QD 0 xœãc``p b6 æ b`…ò‘0'¦¤å—–”–@Ô eò€4 m_ & xœãc``0 b6 æ b`…òᘑ! H i
à
lowcalorie
lowcalorie le 15 Mar 2012
i fixed the first 2 problems so my only problem now is just getting this mess to go away and only have my 3 values show up in my file
Geoff
Geoff le 15 Mar 2012
That 'mess' is the output from the save() function. I gave you two options. If you use save(), use it as I have shown (with the 'ascii' flag). If you use direct file I/O instead, you can get it to fail if you don't want to overwrite an existing file. You said you did want to overwrite, so I used the 'w' flag.

Connectez-vous pour commenter.

Honglei Chen
Honglei Chen le 15 Mar 2012
Use 'w' option to open the file
fid=fopen('testdata','w');
fprintf(fid,'%d %d %d',3,6,9);
fclose(fid);
For details, see
doc fopen

Catégories

En savoir plus sur File Operations dans Centre d'aide et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by