标准IO:分别用fgetc与fputc,fgets与fputs统计文件的行数

xiaoxiao2021-02-27  139

如果对您有帮助就太好了。 1.用fgetc与fputc统计文件的行数

#include<stdio.h> int main(int argc, char *argv[]) { FILE *fp; int ch; if (argc < 2) { printf("Usage:%s <one_file>\n",argv[0]); } if ((fp = fopen(argv[1],"r")) == NULL) { perror("fopen\n"); return -1; } int count = 0; while ((ch = fgetc(fp)) != EOF) { if (ch == '\n') count += 1; } printf("the file is %d line\n",count); fclose(fp); return 0; }

2.用fgets与fputs统计文件的行数

#include<stdio.h> #include<string.h> #define N 64 int main(int argc, char *argv[]) { FILE *fp; char buf[N]; if (argc < 2) { printf("Usage:%s <one_file>\n",argv[0]); } if ((fp = fopen(argv[1],"r")) == NULL) { perror("fopen\n"); return -1; } int count = 0; while (fgets(buf,N,fp) != NULL) { if (buf[strlen(buf)-1] == '\n') count += 1; } printf("the file is %d line\n",count); fclose(fp); return 0; }
转载请注明原文地址: https://www.6miu.com/read-16377.html

最新回复(0)