Click here to Skip to main content
15,889,867 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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:

C++
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;
}
Posted
Updated 17-Nov-18 7:28am

1 solution

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.
 
Share this answer
 
Comments
k5054 18-Nov-18 11:56am    
Since the OP seems to be only interested in the number of lines, and not the contents of the lines, why not use an fread() loop, and just count the number of newlines in the returned string?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900