读取并计算txt文件中的行数 [英] Read and count the number of lines in a txt file

查看:144
本文介绍了读取并计算txt文件中的行数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个typedef结构,我想打印并计算行数。我还有一个SIGTERM,它将结构中的内容复制到txt文件中。我尝试的是错的。我需要更改什么?



我尝试过:



I have 2 typedef structs that i want to print and count the number of lines. I also have a SIGTERM that copies what's in the struct to a txt file. What I tried is wrong. What do I need to change?

What I have tried:

void Print(){           
pid_t pid = getpid();
int count = 0;
int count2 = 0;
char c, d, e, f;
FILE *fp, *fc;

kill(pid, SIGTERM);
fp = fopen("pass.txt", "r");
for( c = getc(fp); c != EOF; c = getc(fp)) {
    if(c == '\n') {
        count = count + 1;
    }
}
printf("Number of lines: %d\n", count);
d = fgetc(fp);
while( d != EOF ) {
    printf("%c", d);
    d = fgetc(fp);
}
fclose(fp);
fc = fopen("cond.txt", "r");
for( e = getc(fc); e!= EOF; e = getc(fc)) {
    if(e == '\n') {
        count2 = count2 + 1;
    }
}
printf("Number of lines: %d\n", count2);
f = fgetc(fc);
while(f != EOF) {
    printf("%c", f);
    f = fgetc(fc);
}
fclose(fc);
return 0;
}

推荐答案

当您读取文件时,文件指针位于文件末尾。您需要倒带或fseek来阅读该文件。



顺便说一下: fgets 可让您的代码更易于理解和紧固。



使用调试器查找代码中发生的情况。



Bonus-tip:将循环包装在函数中。
When you read a file than your file pointer is at the end of the file. You need to rewind or fseek to read the file.

By the way: a fgets would make your code easier to understand and faste.

Use the debugger to find out what is going on in your code.

Bonus-tip: Wrap your loops in functions.


这篇关于读取并计算txt文件中的行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆