I'm going to ask a question maybe as a newbie. I am using the function fwrite
in C to write data double
to a text file, but when I open the file the numbers are not read but a series of symbols and when I use binary files for writing or reading there is no problem (because I do not open them in the editor text), but if I use text files it gives me problems when writing data int
or double
. My sample code:
#include <stdio.h>
int main ( int argc, char **argv )
{
FILE *fp;
unsigned int dinero[10] = { 23, 12, 45, 345, 512, 345, 654, 287,
567, 124 };
fp = fopen ( "fichero.txt", "w" );
fwrite( &dinero[0], sizeof(unsigned int), 10, fp );
fclose ( fp );
return 0;
}
All code examples on the web are like this. Nowhere did I find information if that function is used only with binary files.
From already thank you very much.
Well I will tell a little what I see. Just to contribute something. When I open the file with the gedit editor and type only text, the text is read fine. If I typed text and numbers either int, float or double the text is read but instead of numbers there are jumbled symbols (apparently). If I open it with the sublime text editor and the file contains text and numbers, what I see is the following:
4d6f 7374 7261 6e64 6f20 656c 2075 736f 2064 6520 6677 7269 7465 2065 6e20 756e 2066 6963 6865 726f 2e0a 0100 0000
From what I find out, it is the ascii code of the text plus the number. If the file contains only text, the text is read normally. And if the file contains only numbers sublime text shows me the following:
0100 0000
Enter a single number that is 1. The type of data entered is unsigned int. I look for a way for it to be a binary or something but no. If it is double the file has something else. Well I really went around the bush and my intention was to contribute something but it may not help at all. My question itself is because I can't see the numbers written to a text file if I use the fwrite function. Well my conclusion is that the text can be written in txt files but the numbers must be written in binary files. The 0100 0000 is 1 in hexadecimal. Integers occupy 4 bytes and I have two digits per byte. I can use the function to write and when I read it from the file with fread I save it in an array to work with the numbers. The rest was just curiosity as to why I can't see the text file correctly when I enter numbers.