フィルターのクリア

Editing a .c file using a .m file

4 ビュー (過去 30 日間)
Shrirang
Shrirang 2015 年 2 月 4 日
コメント済み: Shrirang 2015 年 2 月 5 日
I am trying to edit already existing c file using a .m file. I want to insert some characters in .c file. But my code is overwriting the .c file instead of inserting the characters. Following is my code
fileID = fopen('XYZ.c', 'r+'); a = fprintf(fileID,'\n%s\n','XYZ'); fclose(fileID);
Original .c file (just an example) : ABCDEF; ABCDEF; ABCDEF;
After editing the .c file it becomes as follows
XYZ F; ABCDEF; ABCDEF;
My expection was it should not overwrite anything in original c file :
XYZ
ABCDEF; ABCDEF; ABCDEF;
Please guide me how I should get my expected results

採用された回答

Michael Haderlein
Michael Haderlein 2015 年 2 月 4 日
Well, the pointer is at the beginning of the file and that's where the data is written. So the functions behave as they should.
If you wanted to attach some data at the end of the file, you could use the permission 'a+'. In case you want to extend the file at the beginning, I think you need to create an entire new file:
readID=fopen('XYZ.c','r');
writeID=fopen('NEW.c','w');
fprintf(writeID,'%s\n','XYZ');
fwrite(writeID,fread(readID));
fclose(readID);
fclose(writeID);
In principle, you can of course first read the file and then overwrite it (so both files are the same):
fileID=fopen('test.txt','r+');
data=fread(fileID);
frewind(fileID);
fprintf(fileID,'%s\n','XYZ');
fwrite(fileID,data);
fclose(fileID);
edit test.txt
  1 件のコメント
Shrirang
Shrirang 2015 年 2 月 5 日
Yes, Creating a entirely new file is a good idea. Thank you !!!

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

その他の回答 (0 件)

カテゴリ

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