我想在二进制文件中的一行上写三个名字。这该怎么做?例如: 伊万彼得罗夫彼得罗夫。 如果我写
char name[50];
int sizeName;
FILE*fp;
if((fp=fopen("clients.bin","ab+"))==NULL)
{
printf("Error opening the file\n");
exit(1);
}
printf("Enter client's name: \n");
scanf("%s",name);
sizeName=strlen(name);
fwrite(&sizeName,sizeof(int),1,fp);
fwrite(name,sizeName,1,fp);
通过这种方式,我只能在文件中写伊万,但我想要所有3个单词?怎么做@
答案 0 :(得分:2)
问题在于您阅读输入的方式。 scanf()
会在遇到空白时立即停止。因此name
只会存储" Ivan"。 fgets()
可以派上用场。
改变这个:
scanf("%s",name);
到此:
fgets(name, sizeof(name), stdin); // read the line (including the newline from the user's enter hit
name[strlen(name) - 1] = '\0'; // overwrite the newline
你应该得到这个:
Georgioss-MacBook-Pro:~ gsamaras$ gcc -Wall main.c
Georgioss-MacBook-Pro:~ gsamaras$ ./a.out
Enter client's name:
Ivan Petrov Petrov
Ivan Petrov Petrov
打印字符串后,如printf("%s\n", name);
。