该程序旨在将文件作为参数,然后从标准输入读取字符串并将其长度写入文件,然后读取文件的内容(应该包含来自标准输入的字符串的长度)和将其写入标准输出:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define MAX_BUFF 4096
int main(int argc, char **argv)
{
if (argc != 2)
{
puts("you must specify a file!");
return -1;
}
int nRead;
char buffer[MAX_BUFF], tmp;
int fd;
puts("write \"end\" to stop:");
fd = open(argv[1], O_RDWR | O_CREAT | O_APPEND, S_IRWXU);
while ((nRead = read(STDIN_FILENO, buffer, MAX_BUFF)) > 0 && strncmp(buffer,"end", nRead-1) != 0 )
{
if ( write(fd, &nRead, 1) < 0 )
{
perror("write error.");
return -1;
}
}
puts("now i am gonna print the length of the strings:");
lseek(fd, 0, SEEK_SET); //set the offset at start of the file
while ((nRead = read(fd, buffer, 1)) > 0)
{
tmp = (char)buffer[0];
write(STDOUT_FILENO, &tmp, 1);
}
close(fd);
return 0;
}
这是结果:
write "end" to stop:
hello
world
i am a script
end
now i am gonna print the length of the strings:
在写入标准输出之前,我尝试将文件中写入的值转换为 char,但没有成功。我应该如何使用无缓冲 I/O 在标准输出上打印长度?谢谢您的回复
编辑:我用这个改变了从文件中读取的内容:
while((read(fd, &buffer, 1)) > 0)
{
tmp = (int)*buffer;
sprintf(buffer,"%d:", tmp);
read(fd, &buffer[strlen(buffer)], tmp);
write(STDOUT_FILENO, buffer, strlen(buffer));
}
但实际上我无法控制字符串的有效 strlen 因此输出是这样的:
13:ciao atottti
4:wow
o atottti
5:fine
atottti
如您所见, strlength 是正确的,因为它也考虑了换行符。仍然无法控制有效缓冲区大小。