使用putchar()打印行数

时间:2017-05-01 19:09:34

标签: c

请查看我的代码并告诉我为什么我的输出看起来像。

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char** argv) {
   char ch, source_file[20];
   FILE *source;
   int i=1;
   if( argc == 2 ) {
      printf("The file being displayed is %s\n", argv[1]);

   source = fopen(argv[1], "r");

   if( source == NULL )
   {
      printf("Press any key to exit...\n");
      exit(EXIT_FAILURE);
   }

   while( ( ch = fgetc(source) ) != EOF )
   {
       if(ch=='\n')
       {
          putchar(ch);
          printf("%d.", i);
          i++;
       }
       if(i==1)
       {
           printf("%d.", i);
           i++;
           putchar(ch);

       }
       else
          putchar(ch);
   }

   fclose(source);

    return (EXIT_SUCCESS);
}
}

这是输出

C:>p_gui_o3_ex3.exe asd.txt

The file being displayed is asd.txt
1.Teste
2.
Teste
3.
Teste
4.

5.
asd
6.
asd
7.
asd
8.
asd
9.
asd
10.
asd
11.
asd
12.
asd
13.
asd

2 个答案:

答案 0 :(得分:1)

好的问题已得到修复。 输出现在看起来像我想要的,我正在研究你们提供的小技巧。

这是输出

The file being displayed is asd.txt
1.Teste
2.Teste
3.Teste
4.
5.asd
6.asd
7.asd
8.asd
9.asd
10.asd
11.asd
12.asd
13.asd

这是固定代码。

#include <stdio.h>
#include <stdlib.h>

/*
 * 
 */
int main(int argc, char** argv) {
   char source_file[20];
   int ch;
   FILE *source;
   int i=1;
   if( argc == 2 ) {
      printf("The file being displayed is %s\n", argv[1]);

   source = fopen(argv[1], "r");

   if( source == NULL )
   {
      printf("Press any key to exit...\n");
      exit(EXIT_FAILURE);
   }

   while( ( ch = fgetc(source) ) != EOF )
   {
       if(ch=='\n')
       {
          putchar(ch);
          printf("%d.", i);
          i++;
       }
       else if(i==1)
       {
           printf("%d.", i);
           i++;
           putchar(ch);
       }
       else
          putchar(ch);
   }

   fclose(source);

    return (EXIT_SUCCESS);
}
}

感谢大家的帮助。

答案 1 :(得分:0)

  

之前打印行号

要在行之前打印行号,请检测前一个字符是否为'\n'

unsigned long long line = 0;
int previous = '\n';
int ch;

while ((ch = fgetc(source)) != EOF) {
  if (previous == '\n') {
    line++;
    printf("%llu.", line);
  }
  putchar(ch);
  previous = ch;
}

// With files that do not end with a \n, perhaps print a \n anyways
if (previous != '\n') {
  putchar('\n');
}