Question

i have a c project and i have serious problem , i want to open file and replace line number nb (nb is an int) with "*" . this is my code could some one help me please ? it show me the word i want to replace that's mean that the pointer is pointing on the wanted line but nothing happen .help me please

#include <stdio.h>

int main( void )
{
    FILE * f;
    char ch[1024];
    int i, nb;

    i = 0;
    scanf( "%d", &nb ) ;
    f = fopen( "dict.txt", "r+t" );

    while( i < nb )
     {
        fscanf( f, "%s", ch ) ;
        i++;
     }

    printf( "%s", ch );
    fprintf( f, "%s", "****" );
    fclose( f );
}
Was it helpful?

Solution

You've opened the file for reading and writing. According to the MSDN man page for fopen (I am assuming from the r+t mode on the file that you are using Visual Studio):

When the "r+", "w+", or "a+" access type is specified, both reading and writing are allowed (the file is said to be open for "update"). However, when you switch from reading to writing, the input operation must encounter an EOF marker. If there is no EOF, you must use an intervening call to a file positioning function. The file positioning functions are fsetpos, fseek, and rewind.

Some other things to keep in mind:

  • When fscanf reads a string with %s, it reads only one word at a time, not a whole line. It is easier to read whole lines of input with fgets than with fscanf.
  • A file consists of a stream of bytes. If the line you want to replace is 47 characters long, then fprintf(f, "%s", "****") will only replace the first four bytes in the line.
  • That means that if you want to replace line #nb, you will need to read in the line, figure out how long it is, then seek back to the beginning of the line and print out the correct number of asterisks.

Try something like this instead:

#include <stdio.h>
#include <string.h>

int main()
{
    FILE * f;
    char ch[1024];
    int i,nb ;
    fpos_t beginning_of_line;

    i=0;
    scanf("%d",&nb) ;
    f = fopen("dict.txt", "r+t");
    while (i<nb)
      {
        fgetpos(f, &beginning_of_line);
        fgets(ch, 1024, f);
        i++;
      }

    fseek(f, beginning_of_line, SEEK_SET);  // return to beginning of line
    for (i = 0; ch[i] != '\n'; ++i) {
      fputc('*', f);
    }
    fclose(f);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top