我在使用 fread/fwrite 函数读取和写入文件结构时遇到问题。首先,fwrite 编写的文本对我来说是不可读的,但从我看来,它的目的是这样工作的。有没有办法使它成为纯文本,或者它必须是这样的?
另一个问题是,当我尝试使用 fread 函数读取该文件时,最后几个元素没有被读取。
此外,我需要这段代码来直接在磁盘上对文件中的数据进行排序。必须使用 fread/fwrite..
#include <stdio.h>
typedef struct camesi {
char camasa[33];
char culoare[33];
int marime;
char material[33];
} cam;
int main() {
FILE *f, *f2;
int i, j, n;
cam a, b, c;
n = 13;
f = fopen ("new.txt", "w+");
f2 = fopen ("asd.txt", "r");
rewind (f2);
for (i = 0; i < n; i++) {
fscanf (f2, "%s%s%d%s", c.camasa, c.culoare, &c.marime, c.material);
printf ("%s\t%s\t%d\t%s\n", c.camasa, c.culoare, c.marime, c.material);
fwrite (&c, sizeof (cam), 1, f);
}
printf ("\n----------------------------------------\n\n");
rewind (f);
for (i = 0; i < n; i++) {
fread (&c, sizeof (cam), 1, f);
printf ("%s\t%s\t%d\t%s\n", c.camasa, c.culoare, c.marime, c.material);
}
return 0; }
这是控制台的输出:
asdf1 blue 45 skin
asdf2 green 43 skin
asdf3 white 49 skin
asdf4 red 47 skin
asdf5 yellow 54 skin
asdf6 purple 13 skin
asdf7 magenta 74 skin
asdf8 pink 41 skin
asdf9 black 97 skin
asdf10 gray 85 skin
asdf11 orange 26 skin
asdf12 violet 64 skin
asdf13 brown 11 skin
----------------------------------------
asdf1 blue 45 skin
asdf2 green 43 skin
asdf3 white 49 skin
asdf4 red 47 skin
asdf5 yellow 54 skin
asdf6 purple 13 skin
asdf7 magenta 74 skin
asdf8 pink 41 skin
asdf9 black 97 skin
asdf10 gray 85 skin
asdf11 orange 85 skin
asdf11 orange 85 skin
asdf11 orange 85 skin
前半部分是从手动创建的 *.txt 文件中读取的数据。
另一半是使用 fwrite 函数从程序创建的文件中读取的数据。
原始*.txt文件的内容:
asdf1 blue 45 skin
asdf2 green 43 skin
asdf3 white 49 skin
asdf4 red 47 skin
asdf5 yellow 54 skin
asdf6 purple 13 skin
asdf7 magenta 74 skin
asdf8 pink 41 skin
asdf9 black 97 skin
asdf10 gray 85 skin
asdf11 orange 26 skin
asdf12 violet 64 skin
asdf13 brown 11 skin
使用fwrite函数创建的文件内容:
asdf1 €M o ёю( Ђ(wїдЂ‚юяяяblue M - skin M `M А&M €ю( HЯПt M asdf2 €M o ёю( Ђ(wїдЂ‚юяяяgreen M + skin M `M А&M €ю( HЯПt M asdf3 €M o ёю( Ђ(wїдЂ‚юяяяwhite M 1 skin M `M А&M €ю( HЯПt M asdf4 €M o ёю( Ђ(wїдЂ‚юяяяred e M / skin M `M А&M €ю( HЯПt M asdf5 €M o ёю( Ђ(wїдЂ‚юяяяyellow M 6 skin M `M А&M €ю( HЯПt M asdf6 €M o ёю( Ђ(wїдЂ‚юяяяpurple M
skin M `M А&M €ю( HЯПt M asdf7 €M o ёю( Ђ(wїдЂ‚юяяяmagenta M J skin M `M А&M €ю( HЯПt M asdf8 €M o ёю( Ђ(wїдЂ‚юяяяpink ta M ) skin M `M А&M €ю( HЯПt M asdf9 €M o ёю( Ђ(wїдЂ‚юяяяblack a M a skin M `M А&M €ю( HЯПt M asdf10 €M o ёю( Ђ(wїдЂ‚юяяяgray a M U skin M `M А&M €ю( HЯПt M asdf11 €M o ёю( Ђ(wїдЂ‚юяяяorange M skin M `M А&M €ю( HЯПt M asdf12 €M o ёю( Ђ(wїдЂ‚юяяяviolet M @ skin M `M А&M €ю( HЯПt M asdf13 €M o ёю( Ђ(wїдЂ‚юяяяbrown M skin M `M А&M €ю( HЯПt M
最佳答案
asdf11 orange 26 skin
Windows可能会将txt文件中的26视为EOF
关于c - 在 C 中从文件读取/写入结构体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29392977/