我想不斷從文本文件中讀取,但我不知道我在這裏做錯了什麼。它不斷打印我一些不可打印的ascii字符。爲什麼在閱讀txt文件時會出現笑臉字符?
#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;
}
至於我的說法,我通過包含這樣的信息的文件名:
foo-12-
輸出是這樣的:
什麼是您讀取的文件? – ameyCU
當'read'返回'0'時,你爲什麼要調用'puts(buff)'? – Barmar
@ameyCU我在另一個進程中傳遞文件名作爲參數。看看我上面提到的示例文件內容,即'foo-12 -' – Bababarghi