读取并计算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.