0

I want to find the repeated integers and replace their positions with empty space. This is my homework. But I didn't solve this problem. My code is

int main(){

    int control_integer;
    int temp_integer;
    int flag = 0;
    int location;
    char space = ' ';
    char control_end_of_file;

    FILE *fp,*tp;

    fp = fopen("file.txt","r+");

    while(!feof(fp))
    {

        fscanf(fp,"%d",&control_integer); 
        printf("control_integer: %d\n",control_integer );

        while(!feof(fp)){

            fscanf(fp,"%d",&temp_integer);
            printf("temp_integer = %d\n",temp_integer );

            if (temp_integer == control_integer)
            {
                flag = 1;
                printf("girdi integer: %d\n",temp_integer );
                fprintf(fp, "  %c ",space );
            }
        }
    }
    return 0;
}

I planned my function as follows. First I take an element in the file, then I go to a new loop and look at the next elements. If it is equal, I want to replace it with a space. But the problem arises right here. * fp, when the reading operation is performed, the next element is passed but I want to prevent it and write something else to that location. So I want to do both write and delete in the same place. I tried something, but I couldn't do it.

Roberto Caboni
  • 7,252
  • 10
  • 25
  • 39
  • This is the slowest solution. take a look at fseek(...). You may want to consider also: read the whole file first, change the content in memory, write the whole file to disc, either replace or overwrite the existing file – Mario The Spoon Oct 04 '19 at 08:46
  • Are you on a POSIX system(linux/unix etc) ? If yes, I would prefer `mmap(2)` in such cases. – Mihir Luthra Oct 04 '19 at 08:52
  • 1
    Note that [`while (!feof(file))` is always wrong](https://stackoverflow.com/questions/5431941/). – Jonathan Leffler Oct 04 '19 at 08:55
  • 1
    (1) You should keep a record of the numbers you've already seen so that you don't have to rescan from the beginning (using dynamic memory allocation with `malloc()` et al — have you learned about those yet?) (2) You'd normally use `fseek()` and maybe `ftell()` to reposition the read/write pointer. You'd need to track the current position before reading a number; the current position after reading a number; and then if it is a repeat, seek back to the before position and write the appropriate number of spaces to return to the after position. Or, better, copy the unique numbers to a new file. – Jonathan Leffler Oct 04 '19 at 08:59
  • OK I will try fastly thank you. I want to do this without array. – Osman Talha Aydın Oct 04 '19 at 11:11

1 Answers1

0

First I take an element in the file,...

I think in this case int x; x = getc() is enough. E.g.:

while((x = getc(fp)) != EOF){printf("do something");};