user3140854
user3140854

Reputation: 473

Replace an occurrence of a symbol from a file

The following code reads from a file the occurrences of the digit 1. My question is how could such an occurrence be replaced with another number (say '4') and written back again in the file. The while loop will be continued with?

int next;
    FILE *f;
    if (!(f=fopen("C:\\Test\\Sign.txt", "rt"))) 
            {   
              printf("File not existing\n");
            } 
    else{
        while((next=='1')!=EOF)

Upvotes: 0

Views: 41

Answers (1)

user3140854
user3140854

Reputation: 473

The proper solution for that [including the initial one] would be:

#include <stdio.h>
#include <conio.h>
int f(FILE *);
int main(){
    int num=0, next;
    FILE *f;
    if (!(f=fopen("C:\\Test\\Sign.txt", "rt"))) 
            {   
              printf("File not existing\n");
            } 
    else{
       for(;;){
        if((next=fgetc(f))== EOF) break;
        if (next == '1') num++;}
   }
        printf("Found occurrences of digit 1 are %d\n", num);
getch();
}

The for loop counts the occurrences of ones[in this case] whenever it passes through the number with fgetc assigned to the value of next which is 1.

Upvotes: 2

Related Questions