Reputation: 837
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);
}
Upvotes: 0
Views: 221
Reputation: 2248
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. 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.
Upvotes: 1
Reputation: 121961
Apart from the correction stated by pivotnig, fwrite()
does not write a new line character to the file. Either write the new line after the fwrite()
or append it to the addItem
buffer before the fwrite()
.
You should prevent buffer overrun by limiting the number of characters copied to buf
:
scanf("%19s", addItem);
Upvotes: 3
Reputation: 20764
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.
Upvotes: 6