首页 > 解决方案 > 自动换行到文件的问题

问题描述

我在尝试使用给定列将缓冲区写入文件时遇到问题。也许代码不好。但是专业人士的一些指导会很棒。

char buffer[MAX];

int fd_in = open("example.txt", O_RDWR);
if(fd_in == -1)
{
    perror("Error ");
}
int len=strlen(buffer);
while ((len = read(fd_in, buffer, 100)) > 0) {
    for (int i =0, len=strlen(buffer); i < len; i++) {
        if (buffer[i] == '\n') {
            buffer[i] = ' ';
        }
    }
}
int fd_write = open("wrapped.example", O_RDWR | O_CREAT | O_TRUNC, 0644);
char *base, *right_margin;
int length,width;

length = strlen(buffer);
base = buffer;
width = 20;

while(*base)
{
    if(length <= width)
    {
        puts(base);       /* display string */
        write(fd_write, base, length);
        return 0;           /* and leave */
    }
    right_margin = base+width;
    while(!isspace(*right_margin))
    {
        right_margin--;
        if( right_margin == base)
        {
            right_margin += width;
            while(!isspace(*right_margin))
            {
                if( *right_margin == '\0')
                    break;
                right_margin++;
            }
        }
    }
    *right_margin = '\0';
    puts(base);
    write(fd_write, base, length);
    length -= right_margin - base+1;      // +1 for the space 
    base = right_margin + 1;
}

// write(fd_write, buffer, strlen(buffer));

close(fd_in);
close(fd_write);

工作得stdout很好,看起来应该

This is very good
text that has been
put into a file for
the purposes of
being an example.

但是当我查看文件时,它没有与 相同列的宽度,stdout 它看起来像这样

This is a very goodtext that has been put into a file for the purposes of being an example.text that has beenput into a file for the purposes of being an example.put into a file forthe purposes of being an example.the purposes ofbeing an example.being an example.

标签: c

解决方案


推荐阅读