我只想写入文件描述符的是输入字符串。但是,它也会写入在fprintf中传递的错误消息。有人能解释为什么它的行为如此吗?这个小程序显示了行为。为什么stdio.h会打印写入用文件描述符打开的文件?
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
int main(void)
{
int fd;
mode_t mode = S_IRUSR | S_IWUSR;
char *filename = "file.txt";
char *input = "hello world";
char output[20];
// create and close
if((fd = open(filename, O_RDWR | O_CREAT | O_TRUNC, mode)) == -1)
{
fprintf(stderr, "Error.\n");
return -1;
}
close(fd);
// just open
if((fd = open(filename, O_RDWR, mode)) == -1)
{
fprintf(stderr, "Error.\n");
return -1;
}
if(write(fd, input, 200) == -1)
{
fprintf(stderr, "Error.\n");
return -1;
}
// move back to beginning
if(lseek(fd, 0, SEEK_SET) == -1)
{
return -1;
}
if(read(fd, &output, 200) == -1)
{
fprintf(stderr, "Error.\n");
return -1;
}
printf("%s\n", output);
return 0;
}
你没有向我们展示足够的程序来回答你的问题。请提供一个完整的例子。 – 2012-03-06 22:30:01
“即使达到它”是什么意思?即使您的诊断程序正在打印,我似乎也得到了文件输出似乎正在发生的要点。我怀疑你认为发生的事情并不是真的发生,你只是以某种方式迷惑自己。请注意,您的open()调用不会截断文件。你是否检查open()成功,甚至?也许你并没有真的打开文件,文件描述符实际上是不好的。但是当你看文件时,你正在查看正确的文件,并且数据在那里。当您执行ls -l时,文件上的时间戳是什么? – Kaz 2012-03-06 22:34:01
我只想写入文件描述符的是块中的内容。但是,当我在写入文件后打开文件时,它包含块中的消息以及所有fprintf消息,例如无法写入。\ n – Kobi 2012-03-06 22:45:54