无缓冲的I / O:从文件中读取int并将其写入标准输出

时间:2017-10-11 20:31:05

标签: c unbuffered-output

此程序用作参数文件,然后从标准输入读取字符串并将其长度写入文件,然后读取文件的内容(应该包含标准字符串的长度)输入)并将其写入标准输出:

#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是正确的,因为它构成了换行符ttoo。仍然无法控制有效的缓冲区大小。

0 个答案:

没有答案
相关问题