Hi Folks

I need to modify a .txt file using a C program. The file contains name and phone number of my friends like below:

Mark 07915588623
Phill 07542535698
Claire 07825698745
If one of my friends phone number is changed (i.e. Claire 07985413791), how could I modify the file ucsing C codes?

7 Years
Discussion Span
Last Post by Narue

This is a case where you can probably get away with overwriting rather than rewriting. Search for your friend's name, then step forward over the whitespace and simply write the new phone number:

/* Warning: this code was written without the aid of a compiler */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main ( int argc, char *argv[] )
  if  ( argc > 3 ) {
    FILE *stream = fopen ( argv[1], "r+" );
    char name[20];

    if  ( stream == NULL ) {
      perror ( "File open failure" );
      return EXIT_FAILURE;

    while ( fscanf ( stream, "%s ", name ) == 1 ) {
      if ( strcmp ( name, argv[2] ) == 0 ) {
        long pos = ftell ( stream );

        /* Magic: switch to write mode */
        fseek ( stream, pos, SEEK_SET );
        fputs ( argv[3], stream );

  return 0;

Of course you have a problem if you have more than one friend with the same name. Perhaps you should add last names to that file format. ;)


- fopen to open files, fclose to close them
- fgets / fputs to deal with whole lines
- sscanf to parse a line
- sprintf / strcpy / strcat / str.... to generally mess around with char arrays to arrive at the answer you want.


Thanx Narue... but the code didnt work.
Thanx Salem....I need other friends' particulars unchanged.
How to do that?


>Thanx Narue... but the code didnt work.
I can't help you if you don't provide details. Do you take your car to the mechanic and say "It doesn't work"?


> How to do that?
Start with a program which COPIES the file unchanged.
Then add something like "I found Claire"
Then add something. I dunno, lets say prints the old and new phone numbers.


Narue...I've the file name tel.txt. I executed the program like..
c:> parse.exe tel.txt Claire 07985413791

Then it says no such file or directory.


>Then it says no such file or directory.
Then your problem is user error. Make sure the file is in the current working directory when you run the program.

This article has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.