I am trying to write user-entered string data into a file using C.
I am taking input from the user via standard input and then writing that string into a file. I am not using stdio functions like fopen() / fprintf()—instead, I am using Linux system calls such as open() and write().
What I want to do
Take a string input from the user
Write that string into a file
Handle the case where the file does not exist (create it)
Ensure the correct number of bytes are written
code
char Buffer[1024]; fd = open(name, O_WRONLY | O_APPEND); iRet = write(fd, Buffer, sizeof(Buffer)); printf("%d Bytes gets successfully written in file\n", iRet);
Problem
The file gets written, but:
- Extra garbage characters appear in the file, or
- More bytes are written than expected