lte__ lte__ - 3 months ago 17
C Question

C - storing user input in a dynamic char array?

I want to read some string input from the user and write it to a file. Right now I'm doing

char name[25];
scanf("%s", name);
int handle = open("./visitors.txt", O_RDWR|O_CREAT, S_IRUSR|S_IWUSR);
if (handle < 0){
printf("File error.\n");
lseek(handle, -sizeof(name), SEEK_END);
write(handle, name, sizeof(name));

This, of course is not right, since most of the time the user doesn't write 25 characters, only less, so when the user inputs 5 characters, the other 20 will be empty, and I end up having 5 chars the user put in and 20 chars gibberish in my output file. How can I make sure only the user input is being written to the file?


You are using raw system calls to handle the file operations. Unless your intention is specifically to learn about system calls, you should not do that. The write call writes a number of bytes specified by the third parameter. sizeof(name) is wrong in this case. It will not return the length of the string, it will return the length of the entire buffer.

The standard strlen function gives you the string length. So running strlen(name) will give you 5 if the user enters 5 characters, unlike the sizeof you are using.

Unless you want to learn about system calls specifically, you should probably handle file operations with the C standard library, using fprintf to output to file, and functions such as fopen and fclose. Take a look at the fprintf docs that also link to the other functions.