Fprintf and fscanf read and write garbled characters

Source: Internet
Author: User
I was killed when I was writing a Linux file system a few days ago. Today I finally understood it.

This is the CPP File

# Include

# Include

# Include

# Include

Using namespace STD;

Char ch [250];

Struct s {

Short A, B;

};

Int main (){

File * file = fopen ("test.txt", "WT + ");

S st;

St. A = 1, st. B = 2;

Fseek (file, 0, 0 );

Fwrite (& St, sizeof (short), sizeof (ST)/sizeof (short), file );

// Fseek (file, 0, 0 );

// Fread (& St, sizeof (short), sizeof (ST)/sizeof (short), file );

Char temp [256] = "flaf ";

Int C = 0x11110011;

Fseek (file, sizeof (ST), 0); // The result of adding this sentence is different.

Fprintf (file, "% s", temp );

// Fputs (temp, file );

Fwrite (& C, sizeof (INT), 1, file );

Fseek (file, sizeof (ST), 0 );

// Fgets (temp, sizeof (temp), file );

Fscanf (file, "% s", temp );

Fread (& C, sizeof (INT), 1, file );

Cout <temp <"" <C <Endl;

Fclose (File );

System ("pause ");

Return 0;

}

First write a struct in the file, then write a string "flat", and then write an INI-type integer c

When reading a string, the result is followed by garbled characters, and integer c is always correct and sometimes incorrect.

There is a key point here, but I have never realized that the string Terminator \ 0 won't actually be printf in fprintf, just as you can't see the \ 0 on the screen, fprintf just reflects the screen effect to the file.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.