I'm trying to get aquainted with system calls and C. I'm trying to read a file and write all the contents to the command line. I'm trying
int handle = open("./test.txt", O_RDONLY, O_TEXT);
char buf[1];
lseek(handle, 0, SEEK_SET);
while (0 != read(handle, buf, 1)) {
printf(*buf);
}
This ALMOST works, except that it adds some gibberish characters after each character read from the file. For example if the file contains asd asd
this writes a:_s:_d:_ :_a:_s:_d
to the console. Any idea why? How can I fix it?
Every string has to end with the \\0
(null) character.
So try to make your buffer size 2, and just before printf
do buf[1] = '\\0';
In general when you read wcnt (type ssize_t)
number of chars you do buf[wcnt] = '\\0';
Also your printf is not syntaxed correctly safely! printf("%s", buf);
Edit: As mentioned in other answers and comments (I will not add it since I did not propose it first), you can just print a char in this case.
You code should produce warnings on most modern compilers. Because printf()
doesn't accept a char . Since you are reading the file char by char, you can instead use putchar()
to print on the stdout.
while (read(handle, buf, 1) == 1) {
putchar(buf[0]);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.