Skip to content
Home » How to update user information using files in C

How to update user information using files in C

Learn about C Program to update user information using files in the below code example.
Also refer the comments in the code snippet to get a detailed view about what’s actually happening.

C Program to update user information using files :

Let us consider information to be Name, Age and Place. The contents of Input File is :

Olaf 30 Boston
Winny 22 chicago
Elsa 45 Miami.

Here, we are updating Elsa age to 18 and Hence updated contents of Output File will be :

Olaf 30 Boston
Winny 22 chicago
Elsa 18 Miami.

#include<stdio.h>
#include<string.h>
struct details
{
    char name[10];
    int age;
    char city[10];
}arr[10];

//Constructing structure to store values of file
int main()
{
    FILE *fp;
    FILE *fo;
    int i,n=3,newAge;
    char nam[30];
    fp=fopen("input.txt","r");//input file

    /*
      The contents of input file are
      Olaf 30 Boston
      Winny 22 chicago 
      Elsa 45 Miami
    */
    fo=fopen("output.txt","w");//output file
    if(fp==NULL)
	{
		printf("Error cannot open file\n");
	}
    for(i=0;i<n;i++)
	{
		fscanf(fp,"%s %d %s",arr[i].name,&arr[i].age,arr[i].city);		
	}//storing values from file into structure
    printf("Enter name whos age must be changed:");
    scanf("%s",&nam);
    printf("Enter new age:");
    scanf("%d",&newAge);
    for(i=0;i<n;i++)
    {
        if(strcmp(nam,arr[i].name)==0)
        {
            arr[i].age=newAge;
        }
    }//changing values in struct accordingly with name elsa
    if(fo==NULL)
	{
		printf("Error cannot open file\n");
	}
    for(i=0;i<n;i++)
	{
	   fprintf(fo,"%s\t%d\t%s\n",arr[i].name,arr[i].age,arr[i].city);
	}//printing modified content into output file

    /*
      The contents of output file are
      Olaf 30 Boston
      Winny 22 chicago 
      Elsa 18 Miami
    */
    fclose(fp);
    fclose(fo);
    return 0;
}

Input/Output Specification:

Enter name who’s age must be changed: Elsa
Enter new age: 18

This is simple Example on updating values of file .It is done using structures. Here, Structures are used as a medium to update data in a file. This Format can be used as a reference for other modifications as well.

Hope above code works for you and Refer the below Related Codes to gain more insights. Happy coding and come back again.