Reputation: 47
My program is supposed to print the text contained in a text file, which is saved in the same directory as both the source code and the executable, and then print the number of lines. However, the output is some random characters. I am using ubuntu.
Follow up question: which one has to be in the same directory as the file (if I don't specify the absolute path), the executable or the source code? Thanks in advance.
#include <stdio.h>
#include <stdlib.h>
int main(){
char c;
int i = 0;
FILE *fp = fopen("newfile","r");
if(!fp) {
printf("Error opening\n");
return -1;
}
printf("Text of newfile: \n");
while(fgetc(fp)!=EOF){
c = fgetc(fp);
printf("%c",c);
if(c == '\n')
++i;
}
fclose(fp);
fp = NULL;
printf("\nThere are %d lines in the file\n",i+1);
return 0;
}
The file cointains the text:
this is my file
this is line 2
output:
Text of newfile:
hsi yfl
hsi ie2�
There are 2 lines in the file
Upvotes: 1
Views: 480
Reputation: 310970
For starters you are using fgetc
two times in the loop
while(fgetc(fp)!=EOF){
^^^^^^^^^
c = fgetc(fp);
^^^^^^^^^
//...
Secondly the variable c
must be declared as having the type int
.
The loop can look the following way
int c;
//...
while ( ( c = fgetc( fp ) ) != EOF )
{
putchar( c );
if ( c == '\n' ) ++i;
}
Upvotes: 4