c - 自动换行到文件的问题
问题描述
我在尝试使用给定列将缓冲区写入文件时遇到问题。也许代码不好。但是专业人士的一些指导会很棒。
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.
解决方案
推荐阅读
- java - 我如何在java中增加静态变量
- git - Git 功能分支将开发分支作为父分支
- swift - 当 textField 包含两个子字符串时,Open Weather Map 会识别城市名称
- verilog - 奇偶校验检查器使用verilog的任务
- c# - BitConverter.ToSingle 截断浮点值
- python - 由于缺少 DLL,Python EXE 运行失败
- python - 如何基于构造函数参数创建具有类属性的子类,以便在 GridSearchCV 的估计器中使用?
- python - 如何获取日期之间的时间段?
- sql - 删除/删除列 SQL 中的值
- c# - blob 流长度属性值始终为 -1,无论文件是否为空