I have a bit of Matlab code and I am trying to export some string and create a tab-delimitted text file from it. I think fprintf performs similarly in C (if not please edit my tag). I believe my issue is with my format string. Basically I have 7 strings that I want separated by tabs and then a newline character. please note that “fid” is a full path. I am looping this in a for loop so lines are being appended each pass and the file is built.
ImgData = strcat(ImgData, fid, '\t', imgNumber, '\t', N_std,'\t',S,'\t',N,'\t',SNR,'\t',SNR_dB,'\n');
DataOut = fopen(strcat('Image_F', folderNumber, '_Data.txt'), 'w');
fprintf(DataOut,'%s\t %s\t %s\t %s\t %s\t %s\t %s\n',ImgData);
You may be curious on how this exports. This formats like
fid\tI#\tN_std\tS\tN\tSNR\tSNR_dB\n
in the txt file. As you can tell this isn’t tab-delimitted which my major issue. I am having some trouble with the format string. Does anyone know how to reformat it so it prints the tabs and newline?
You’re creating a string in
ImgDatathat you then pass as input tofprintf. This readsImgDatainto the first%sof the format string, and then adds at least one tab at the end.What you should do instead is write something like:
which assumes that
imgNameis a string andimgNumberan integer number. Note that I pass two placeholders (with the %-sign) and two input variables to fprintf.Use
%6.2fprint floating point numbers with a total of 6 characters, including 2 after the comma, forSNR, for example.For easier development, you can drop the first input argument to
fprintf, in which case it will print to command line.