Unable to correctly write data in a text file

末鹿安然 提交于 2021-02-17 03:43:05

问题


I wrote the following program to print 200 random number in a file:

int main() 
{
    FILE * fp; 
    fp = fopen ( "myfile.txt", "w" ) ;
    if ( fp == NULL )
    {
        printf ( "Unable to create file." ) ;
        exit ( 0 ) ;
    }

    int i, noofr=200, j ; 

    for ( i = 0 ; i < noofr ; i++ )
    {
        j = rand ()%100 ;
        fwrite ( &j, sizeof ( int ), 1, fp ) ;
        printf ( "%d\t", j ) ;
    }

    fclose ( fp ) ;

    printf ( "\nFile is created. \nPress any key to continue." ) ;

    return 0;

}

On the console the number are printing correctly, but in the file, I see:

) C " E N : > @ - Q = [ _ * $ [ 5 \ R _ / G & E
C c # ^ ! I @ ) 5 D / , > 9 % ; ) N # Z * X ( * @ 0 .
Z F 2 ] 0 T 6 8 ( B L
, ' % & R ) ! ' : M
I V - H F M I a V Z = $ 7 C 7 J 4 2 2 ) B [ % 9 W 5 S - : X . D [ > 7 ; % 0 S _ ) 2 [ $ J ` 0 c D T Q " 5 c & X C ] 0 S

I am running the above program on windows 7 32 bit with visual studio 2010.

What is wrong here?


回答1:


The fwrite function writes a chunk of memory to a file and your chunk of memory in this case is an integer in binary form. For example, the decimal integer 314,159 (4CB2F16) in 32-bit big-endian format would be stored in memory as the hex digits:

+----+----+----+----+
| 00 | 04 | CB | 2F |
+----+----+----+----+

So writing that memory block to a file will generally not result in anything readable by a human, unless you have an unusual number like 1348565002 or 175661392 (depending on the endian-ness).

In order to write your integer in human-readable format, you just use fprintf, very similar to the way you used it to print to standard output:

fprintf (fp, "%d\t", j);
printf ("%d\t", j ) ;



回答2:


Your problem lies with the fact that you have used the fwrite function instead of the fprintf function.

The fwrite function is a function commonly used to write binary data into a file. The data which we read in a file is generally ASCII. ASCII text uses 1 byte (8 bits or 8 0/1 places to fill) to represent each character. Now when you put binary data into a file you are placing 1's or 0's one by one into the file.

Now when you opened the file each of the 1's and 0's got converted into their corresponding ASCII value.

To use the fprintf function, it is exactly similar to the printf function: fprintf(fp,"%d",j);

If you wish for more info:

http://www.c4learn.com/c-programming/c-reference/fwrite-function/

http://www.c4learn.com/c-programming/c-reference/fprintf-function/



来源:https://stackoverflow.com/questions/26970207/unable-to-correctly-write-data-in-a-text-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!