How to use ungetc() function to unget character from file in C

2 Answers

0 votes
int main(void)
{
	int ch;
	char buf[64];

	FILE *fp = fopen("d:\\data.txt","rt");
	if (fp == NULL) 
	{
		perror("Error open file");
		return 1;
	}
	while (!feof(fp)) 
	{
		ch = getc(fp);
		if (ch == EOF) break;
		// replace A with 3 // first char only
		if (ch == 'A') 
			ungetc('3', fp);
		else 
			ungetc(ch, fp);
		if (fgets(buf, 64, fp) != NULL)
			fputs(buf, stdout);
		else 
			break;
	}

    fclose(fp);

    return 0;
}
  
/*
run:
  
3BCDEFGHIJKLMNOPQRSTUVWXYZ

*/

 



answered May 7, 2016 by avibootz
edited May 7, 2016 by avibootz
0 votes
int main(void)
{
	int ch;

	FILE *fp = fopen("d:\\data.txt","rt");
	if (fp == NULL) 
	{
		perror("Error open file");
		return 1;
	}
	while ((ch = getc(fp)) != EOF)   
	{
		// replace C with 3 
		if (ch == 'C') 
			ungetc('3', fp);
		else 
			ungetc(ch, fp);
		
		putc(getc(fp), stdout);
	}

    fclose(fp);

    return 0;
}
  
/*
run:
  
AB3DEFGHIJKLMNOPQRSTUVWXYZ

*/

 



answered May 7, 2016 by avibootz
edited May 7, 2016 by avibootz
...