overwrite a text file with other data

42 ビュー (過去 30 日間)
lowcalorie
lowcalorie 2012 年 3 月 15 日
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

回答 (2 件)

Geoff
Geoff 2012 年 3 月 15 日
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 件のコメント
lowcalorie
lowcalorie 2012 年 3 月 15 日
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 2012 年 3 月 15 日
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.

サインインしてコメントする。


Honglei Chen
Honglei Chen 2012 年 3 月 15 日
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

カテゴリ

Help Center および File ExchangeLow-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