已知在ubuntu系统中存在一个testcatc文件请修改testcatc的源代码使得打印内容时可以同时输出行号即testcat -n testcatc的效果与运行cat -n testcatc的效果相同testcatc的源代码如下:#includesystypesh#includesysstath#includefcntlh#includeunistdh#includeerrnoh#inclu
修改后的源代码如下:
#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(line_num == 1){ // 第一行需要单独处理
printf(" %d ", line_num);
line_num++;
}
if(buf[i] == '\n'){ // 遇到换行打印行号
printf("%c %d ", buf[i], line_num);
line_num++;
}else{
printf("%c", buf[i]);
}
}
}
}
if(fd>0){
close(fd);
}
return 0;
}
修改思路:
- 添加一个行号计数器line_num,初始化为1。
- 在每次打印文件内容时,遍历每个字符,如果遇到换行符就打印行号并将行号计数器+1,否则不打印行号。
- 对第一行单独处理,因为第一行之前没有换行符。
- 输出格式与cat -n命令一致
原文地址: https://www.cveoy.top/t/topic/dHyJ 著作权归作者所有。请勿转载和采集!