1,105,331 Community Members

Reading characters from a file

Member Avatar
TMDG
Newbie Poster
2 posts since Feb 2012
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

I am wondering how to read a file in c... this requires some more background information before you give me something useless

What I have so far:

#include <stdio.h>

int main(void)
{
	FILE *fpr,*fpw;
	char C;
	int I;
	
	fpr = fopen("cwM.dat","r");
	fpw = fopen("echocwM.dat","w");
	
	while (C != EOF)
	{
		fscanf(fpr,"%c",&C);
		fprintf(fpw,"%c",C);
		I = C;
		printf("%d\n",I);
	}

	fclose(fpr);fclose(fpw);
	
	return 0;
}

my real question is what if the file I'm trying to read is: ÿdÿ before you post a solution, check your code against the above file.

Member Avatar
zeroliken
Nearly a Posting Virtuoso
1,222 posts since Nov 2011
Reputation Points: 79 [?]
Q&As Helped to Solve: 216 [?]
Skill Endorsements: 15 [?]
 
0
 

use "wb" and "rb" for writing and reading in data files

Member Avatar
WaltP
Posting Sage w/ dash of thyme
9,363 posts since May 2006
Reputation Points: 2,905 [?]
Q&As Helped to Solve: 1,151 [?]
Skill Endorsements: 45 [?]
Team Colleague
 
2
 

For me the question would be why would you use fscanf() to read a single character when fgetc() does it much more efficiently?

Member Avatar
TMDG
Newbie Poster
2 posts since Feb 2012
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Thank You WaltP for pointing me to fgetc() I was looking through the MAN pages and was able to fix my problem by using ftell() to see if the offset stopped changing after each read as follows:

#include <stdio.h>

int main(void)
{
	FILE *fpr,*fpw;
	char C;
	int I, i, EC, t, tl;
	
	fpr = fopen("cwM.dat","r");
	fpw = fopen("echocwM.dat","w");
	EC=0;
	t = ftell(fpr);
	printf("%d\n",t);
	tl=t;
	for(;;)
	{
		C = fgetc(fpr);
		t=ftell(fpr);
		printf("%d\n",t);
		if (t == tl)
		{
			break;
		}
		else
		{
			tl = t;
		}
		fprintf(fpw,"%c",C);
		I = C;
		if (I < 0)
		{
			I += 256;
		}
	}

	fclose(fpr);fclose(fpw);
	
	return 0;
}
Question Answered as of 2 Years Ago by WaltP and zeroliken
Member Avatar
WaltP
Posting Sage w/ dash of thyme
9,363 posts since May 2006
Reputation Points: 2,905 [?]
Q&As Helped to Solve: 1,151 [?]
Skill Endorsements: 45 [?]
Team Colleague
 
0
 

Thank You WaltP for pointing me to fgetc()

You're welcome....

I was looking through the MAN pages and was able to fix my problem by using ftell() to see if the offset stopped changing after each read as follows:

Terrible idea. Why not just test the return of fgetc() and process the error or EOF?

You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: