Q:

C program read integers and appends sum to the end in File Handling

0

Write a C program read integers and appends sum to the end in File Handling. Here’s simple program read integers and appends sum to the end in File Handling in C Programming Language.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Below is the source code for C program read integers and appends sum to the end in File Handling which is successfully compiled and run on Windows System to produce desired output as shown below :

 
 


SOURCE CODE : :

/*  C program read integers and appends sum to the end in File Handling  */

#include<stdio.h>
#include<conio.h>
#include<process.h>

int main()
{
    int a,i,n,sum=0;
    FILE *fp;

    //Writing numbers to the file
    fp=fopen("C:\\Users\\acer\\Documents\\file4.txt","w");
    if(fp==NULL)
    {
    printf("File could not open!!");
    exit(0);
    }

    printf("How many numbers? ");
    scanf("%d",&n);
    printf("\nEnter numbers in the file:\n");

    for(i=0;i<n;++i)
    {
    scanf("%d",&a);
    putw(a,fp);
    }
    fclose(fp);

    //Reading the file and doing sum
    fp=fopen("C:\\Users\\acer\\Documents\\file4.txt","r");
    if(fp==NULL)
    {
    printf("File could not open!!");
    exit(0);
    }

    while((a=getw(fp))!=EOF)
    sum+=a;

    fclose(fp);

    //Appending sum to the file
    fp=fopen("C:\\Users\\acer\\Documents\\file4.txt","a");
    if(fp==NULL)
    {
    printf("File could not open!!");
    exit(0);
    }

    putw(sum,fp);
    fclose(fp);

    //Displaying file after append
    fp=fopen("C:\\Users\\acer\\Documents\\file4.txt","r");
    if(fp==NULL)
    {
    printf("File could not open!!");
    exit(0);
    }

    printf("\nFile after append:\n");
    while((a=getw(fp))!=EOF)
    printf("%d ",a);

    fclose(fp);

    return 0;

}

OUTPUT : :


/*  C program read integers and appends sum to the end in File Handling  */

How many numbers? 6

Enter numbers in the file:
1
2
3
4
5
6

File after append:
1 2 3 4 5 6 21

Process returned 0

Above is the source code for C program read integers and appends sum to the end in File Handling which is successfully compiled and run on Windows System.The Output of the program is shown above .

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Write a C program to Merge two files using file ha... >>
<< Write a C program to Read and Write student record...