简体   繁体   English

在C中将字符串添加到文本文件

[英]Adding Strings to a Text File in C

I am making a grocery list program and I want to include a user-input string that is put it in the next available line in the text file. 我正在制作一个杂货清单程序,我想在文本文件的下一个可用行中包含一个用户输入的字符串。 Right now this adds the string to the file, but it then puts in random characters for a number of spaces and then, if I input something else, it won't be on the next line. 现在,这会将字符串添加到文件中,但随后会在多个空格中放入随机字符,然后,如果我输入其他内容,它将不在下一行。

void AddToFile(FILE *a) {
    char addItem[20];
    printf("Enter item: ");
    scanf("%s", &addItem);
    fwrite(addItem, sizeof(addItem), 1, a);
}

this line should be: 这行应该是:

    // strlen instead of sizeof
    fwrite(addItem, strlen(addItem), sizeof(char), a); 

Your code always writes 20 characters, instead of the real number of characters that the string has. 您的代码始终写入20个字符,而不是字符串具有的实际字符数。

Apart from the correction stated by pivotnig, fwrite() does not write a new line character to the file. 除了pivotenig指出的更正之外, fwrite()不会在文件中写入换行符。 Either write the new line after the fwrite() or append it to the addItem buffer before the fwrite() . fwrite()之后编写新行,或将其附加到fwrite()之前的addItem缓冲区中。

You should prevent buffer overrun by limiting the number of characters copied to buf : 您应该通过限制复制到buf的字符数来防止缓冲区溢出:

scanf("%19s", addItem);

In the current example, if you will try to write an item with more than 20 characters you will get into trouble as scanf will overwrite non allocated memory. 在当前示例中,如果您尝试写一个超过20个字符的项目,则将遇到麻烦,因为scanf将覆盖未分配的内存。 A slightly improved version would be: 稍作改进的版本将是:

scanf("%19s",&addItem);

In this way, at least you will not overwrite random memory. 这样,至少您不会覆盖随机内存。

Edit: Thanks to Jack for pointing out \\0 has to be written also. 编辑:感谢杰克指出\\ 0也必须写。

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

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