写程序完成文件显示功能,把命令行参数作为文件名,显示指定文件内容,要求在显示时加上行号。

2024-12-21 16:13:33
推荐回答(1个)
回答1:

#include

int main(int argc, const char *argv[])
{
FILE *fp;
int line, print_num;
char ch;

if (argc != 2) {
printf("Usage:\t%s filename\n", argv[0]);
return 1;
}

fp = fopen(argv[1], "rt");
if (fp == NULL) {
printf("Unable to open %s\n", argv[1]);
return 1;
}

line = 1;
printf("%04d: ",line);
print_num = 0;
while (!feof(fp)) {
ch = fgetc(fp);
if (ch == '\n') {
line++;
print_num = 1;
continue;
}
if (ch == EOF)
break;

if (print_num) {
printf("\n%04d: ",line);
print_num = 0;
}
printf("%c", ch);
}

printf("\n");
fclose(fp);
return 0;
}