Adding a header to a .txt file

83 次查看(过去 30 天)
Deezy
Deezy 2012-8-13
I have a code right now where I ask the user to select the text file that has 3 columns of data. I am currently adding a timestamp and exporting the text file back out to the user... what I could use help on is adding a header to the top of the data. I don't know what commands to write in my code in order to do this. Any suggestions at all would be greatly appreciated!!

回答(2 个)

Jürgen
Jürgen 2012-8-13
编辑:Walter Roberson 2012-8-13
I am not 100% sure what you are trying to do but if you want to write to a text file, that is quite well explained in the help of Matlab with an example, see below,
if first you read your data ( 3 columns) to a matlab matrix then open a new text file, write the header with fprintf then add the data, also with fprintf ( see example below) finally close the file,
probably you can also first open the orginal txtfile and add the header before the data, but I do not know the command by heart, I know you can append txt using fprintf with "a"
hope this helps a bit
regards,J
% create a matrix y, with two rows
x = 0:0.1:1;
y = [x; exp(x)];
% open a file for writing
fid = fopen('exptable.txt', 'w');
% print a title, followed by a blank line
fprintf(fid, 'Exponential Function\n\n');
% print values in column order
% two values appear on each row of the file
fprintf(fid, '%f %f\n', y);
fclose(fid);

Walter Roberson
Walter Roberson 2012-8-13
There is no mechanism to insert into a file, only mechanisms to overwrite within a file and mechanisms to create new files.
Jürgen's suggestion of reading the data in, creating a new file, writing the header, and then writing the data, is a workable solution (provided the file fits into memory.) It could be followed by renaming the new file to the old name.
Also workable:
fidin = fopen('InputFile.txt', 'rt');
fidout = fopen('OutputFile.txt', 'wt');
fprintf(fidout, '%s\n', 'The Header Goes Here');
while true
thisline = fgets(fidin);
if ~ischar(thisline); break; end %end of file
fwrite(fidout, thisline);
end
fclose(fidout);
fclose(fidin);
And then rename the new file to the old one.

Community Treasure Hunt

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

Start Hunting!

Translated by