My .txt file I have created before running the code looks like the following:
/*
I am Jason and I love horses hahaha/n
This is amazing, How much I love horses, I think I am in love/n
how many people love horses like I do?/n/n
this is quite a horsed up paragraph
*/
//I also manually wrote '\0' character at the end of my string//
And the output that I am wanting for this program is the same as above, and the code is the following:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
FILE *filepointer;
int buck;
int counter=1 ;
filepointer = fopen("inoutproj.txt","r");
while(buck=fgetc(filepointer),buck!=EOF)
{
if(buck=='\n')
{
++counter;
}
printf("%c",fgetc(filepointer));
}
printf("\nThere are %d lines in the text file\n\n",counter);
counter=1;
rewind(filepointer);
for(buck=fgetc(filepointer);buck<175;++buck)
{
if(fgetc(filepointer)=='\n')
{
++counter;
}
printf("%c",fgetc(filepointer));
}
printf("\nThere are %d lines in the text file\n",counter);
fclose(filepointer);
return 0;
the output is the following:
mJsnadIlv osshhh
Ti saaig o uhIlv oss hn mi oe o aypol oehre ieId?
hsi ut osdu aarp�
There are 3 lines in the text file
a ao n oehre aaa hsi mzn,Hwmc oehre,ItikIa nlv
hwmn epelv osslk o
ti sqieahre pprgah���������������
There are 3 lines in the text file
As you can see I tried two different approaches with fgetc
(While loop and a for loop), but the output is still coming out broken. I have read some archived Macbook Pro document that the loops are reading the pushed back input from the input stream, and it seems to persistently do that for my code too (or maybe I am wrong).
Can someone tell me what is wrong with the code I have written and why my computer is not outputting the .txt file as I desire?
I am currently running Cygwin GCC on VSCode.
My system is a Macbook Pro 16in 2019
You are reading 2 characters for every one you print. The first character was read by "buck=fgetc(filepointer)" as an argument in the while statement. The second character was read by "printf("%c",fgetc(filepointer));".
So essentially your program first reads a character from the file and stores it in "buck", then reading another character and printing it out, resulting in the output missing characters.
You can do something like this:
FILE *filepointer;
int buck;
int counter=1 ;
filepointer = fopen("inoutproj.txt","r");
while(buck=fgetc(filepointer),buck!=EOF)
{
if(buck=='\n')
{
++counter;
}
printf("%c",buck);
}
printf("\nThere are %d lines in the text file\n\n",counter);
To simply print buck for every scan. Good luck!