Terrornado
Terrornado

Reputation: 843

Data stored in text file using fwrite is unreadable in C

When data is stored on a text file using fwrite, like this, where t is a struct:

fwrite(&t, sizeof(t), 1, fptr);

The output in the text file ends up as:

楷獬湯찀쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌쳌敷敷

(Above is a sample, not the full output)

Why does this happen?

Edit: t is a struct - where user is prompted for two strings, username and password. Here's a basic template - it was a friend who had the problem and I don't have the actual code snippet with me to share, but I assume it was something equivalent to this. I know it's not very helpful, sorry about that. Any help is appreciated.

struct details {
char username[32], password[32];
}

int main() {
struct details t;
scanf("%s",t.username);
scanf("%s",t.password);
}

File is opened as a+ mode.

Edit2: Ran friend's code, initialized struct with new file, inputting username and password as '0'. Here's the hexdump.

file name: admins.txt
mime type: 

0000-0010:  30 00 cc cc-cc cc cc cc-cc cc cc cc-cc cc cc cc  0....... ........
0000-0020:  cc cc cc cc-cc cc cc cc-cc cc cc cc-cc cc cc cc  ........ ........
0000-0030:  cc cc cc cc-cc cc cc cc-cc cc cc cc-cc cc cc cc  ........ ........
0000-0040:  cc cc cc cc-cc cc cc cc-cc cc cc cc-cc cc cc cc  ........ ........
0000-0050:  cc cc cc cc-cc cc cc cc-cc cc cc cc-cc cc cc cc  ........ ........
0000-0060:  30 00 cc cc-cc cc cc cc-cc cc cc cc-cc cc cc cc  0....... ........
0000-0070:  cc cc cc cc-cc cc cc cc-cc cc cc cc-cc cc cc cc  ........ ........
0000-0080:  cc cc cc cc-cc cc cc cc-cc cc cc cc-cc cc cc cc  ........ ........
0000-0090:  cc cc cc cc-cc cc cc cc-cc cc cc cc-cc cc cc cc  ........ ........
0000-00a0:  cc cc cc cc-cc cc cc cc-cc cc cc cc-cc cc cc cc  ........ ........

Upvotes: 1

Views: 714

Answers (2)

Read documentation of fwrite. It is for binary IO. But you have a textual format.

You could consider parsing your textual file. Learn about fgets, sscanf, etc...

Consider also using existing textual formats like JSON, YAML, etc... You'll find many libraries for them (e.g. jansson in C).

Since you are interested in (or are observing) Chinese characters, read Utf8 Everywhere.

Also, compile your code with all warnings and debug info (e.g. gcc -Wall -Wextra -g with GCC) and learn how to use the gdb debugger to understand the behaviour of your program. You might use watchpoints to understand when a location is written.

Read much more about undefined behavior and be scared of it (junk file content is a possible effect of UB, but it could be much worse).

Upvotes: 1

Vinay P
Vinay P

Reputation: 635

Is user entered input a Unicode string? Initialize struct to all zeros. Paste hexdump of the file.

Upvotes: 0

Related Questions