简体   繁体   English

fwrite 在 C 中,它不会在文件中写入正确的单词

[英]fwrite in C, it doesn't write the correct word in file

I think this is a simple question but I can't get around to find the answer.我认为这是一个简单的问题,但我无法找到答案。

I want to write an array into a file.我想将数组写入文件。 text is the array and number is the number of words in the array. text是数组, number是数组中的单词数。

It runs but in the newfile.txt I don't get the text I want.它运行但在newfile.txt中我没有得到我想要的文本。 It prints chinese characters, a lot of spaces.它打印汉字,很多空格。 In shorts it's a mess.简而言之,这是一团糟。 The problem, I think, is what I store in the memory but I can't figure out how to resolve it.我认为问题在于我存储在 memory 中,但我不知道如何解决它。

Thank you in advance: :)先感谢您: :)

void makefile(char **text,int number) {
    FILE * mf;
    mf = fopen("newfile.txt", "wt");
    fwrite(text,sizeof(text),number,mf);
    fclose(mf);
}

Parameter char **text is a pointer to an array of pointers, each of them pointing to a line of text to be printed.参数char **text是指向指针数组的指针,每个指针都指向要打印的一行文本。 So you will need a loop to iterate over these pointers and write each of them separately.因此,您将需要一个循环来迭代这些指针并分别编写它们中的每一个。 Otherwise, you write a number of addresses in binary format rather than any text, and that's the mess you observe in the file then.否则,您会以二进制格式而不是任何文本写入许多地址,这就是您在文件中观察到的混乱。

The loop could look as follows:循环可能如下所示:

for (int i=0;i<number;i++) {
   fputs(text[i], mf);
}

If, for some reason, you need to use fwrite , you would write:如果由于某种原因,您需要使用fwrite ,您将编写:

for (int i=0;i<number;i++) {
   fwrite(text[i],1,strlen(text[i]),mf);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM