#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
int main () {
char grade[5];
char name[30];
int fd = creat("notas.txt", 0644);
if (fd == -1) {
perror("notas.txt")开发者_如何学Python;
return 1;
}
while (1) {
scanf("%s %s", name, grade);
if (strcmp(name, "end") != 0) {
write(fd, name, 30);
write(fd, "\t", 1);
write(fd, grade, 5);
write(fd, "\n", 1);
} else {
close(fd);
return 0;
}
}
}
Hi everyone. I am trying to get into *nix Kernel API programming and I wrote the above program. It reads names and grades from the command line and then writes them to a file. However, the file is garbled, I can only cat
it (doesn't open with a text editor) and my data appears among a a torrent of garbled random chars. After cat
ing the file, my prompt also has a bunch of leading random chars like 1C2;1C3
(...).
Why does this happen?
Thank you all.
write()
writes bytes to a file, not specifically strings. The third parameter to write()
is the number of bytes to write. write(fd, name, 30)
thus writes 30 bytes to the file, but the string in name
is shorter, so a bunch of random characters which happen to be in memory get written to the file.
In C the length of a string is indicated by putting a nul character ('\0'
, which is 0) at the end of the string, and can be checked with the strlen()
function, so you need to write write(fd, name, strlen(name))
.
精彩评论