我需要读取一个文件,然后将其打印到STDOUT但是间隔为两倍.到目前为止我所拥有的是:
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#define BUFSZ 1024
int main(int argc, char* argv[]){
int n, fdin;
char buf[BUFSZ];
if ((fdin=open(argv[1],O_RDONLY))<0){
perror(argv[1]);
exit(-1);
}
while(( n = read(fdin, buf, BUFSZ))>0){
if(write(STDOUT_FILENO,buf,n) != n){
fprintf(stderr, "Write Error\n");
exit(-1);
}
printf("\n");
}
close(fdin);
return(0);
}
Run Code Online (Sandbox Code Playgroud)
我是C的新手并且不知道如何在代码中实现\n,我的printf("\n")在尝试将整个文件的内容加倍空间时毫无用处.我想我必须将\n添加到读取中?但我不完全确定这是否正确或如何做到这一点.
read()当它遇到一个新行字符时不会停止读取,因此发布代码中的算法很容易错过写一个空行,因为它read()可以读取多行.
一种更简单的方法可以使用fgets():
FILE* f = fopen(argv[1], "r");
if (f)
{
char buf[BUFSZ];
while (fgets(buf, BUFSZ, f))
{
printf("%s", buf);
/* fgets() may not have read a full line if the
length of the line was greater than BUFSZ,
so check it did before double spacing. */
if (strrchr(buf, '\n')) printf("\n");
}
fclose(f);
}
Run Code Online (Sandbox Code Playgroud)