请修改下面的代码使得打印内容时可以同时输出行号:#includesystypesh#includesysstath#includefcntlh#includeunistdh#includeerrnoh#includestdioh#includestringh#define BUF_SIZE 30int mainint argc char argv char bufBUF_SIZE; int len
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<errno.h>
#include<stdio.h> #include<string.h>
#define BUF_SIZE 30
int main(int argc, char* argv[]) { char buf[BUF_SIZE]; int len = 0; int fd = -1; int line_num = 1; // 新添加的行号变量
if (argc != 2) {
printf("wrong parameters\n");
return -1;
}
fd = open(argv[1], O_RDONLY);
if (fd == -1) {
printf("error in open file");
printf("the error is: %s\n", strerror(errno));
return -1;
}
else {
//printf("open file success\n");
while ((len = read(fd, buf, BUF_SIZE)) != 0) {
for (int i = 0; i < len; i++) {
if (buf[i] == '\n') {
printf("%d: ", line_num++); // 输出行号
}
write(STDOUT_FILENO, &buf[i], 1);
}
}
}
if (fd > 0) {
close(fd);
}
return 0;
}
原文地址: https://www.cveoy.top/t/topic/du4x 著作权归作者所有。请勿转载和采集!