c - Why do I get smiley characters while reading a txt file? -
i trying continuously read text file don't know doing wrong here. keeps printing me non-printable ascii characters.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <signal.h> #include <fcntl.h> #include <errno.h> #include <sys/types.h> #include "windows.h" int main(int argc, char **argv) { int n, fd; char buff[256]; if (argc != 2) { fprintf(stderr, "usage: %s <filename>\n", argv[0]); return 1; } fd = open(argv[1], o_rdonly); if (fd < 0) { perror("open"); return 1; } else if (lseek(fd, 0, seek_end) < 0) { perror("lseek"); return 1; } else { while (1) { n = read(fd, buff, sizeof(buff)); if (n < 0) { perror("read"); break; } if (n == 0) { puts(buff); sleep(100); continue; } if (write(stdout_fileno, buff, n) < 0) { perror("write"); break; } } } return 0; } as argument, pass filename contains information this:
foo-12- the output this:
the problem line:
puts(buff); when read() returns 0, means you've reached end of file, there's nothing print. printed contents of file in previous iterations of loop, on line with:
write(stdout_fileno, buff, n) the puts() printing whatever garbage happens in buff. , since buff isn't null-terminated, may continue printing far past end of array, until finds null byte.
get rid of line.
the reason you're not printing contents of file because @ beginning do:
lseek(fd, 0, seek_end) this goes end of file before tries read anything. program display contents added file after start program. because of sleep(100), wait 100 seconds before prints next chunk.

Comments
Post a Comment