0

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);
}
1
  • do this with the other questions as well. Commented Apr 18, 2012 at 13:04

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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);

Comments

1

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.

1 Comment

You must reserve one space in addItem for 0-terminator,\0.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.