File Handling Exercise

 Here are some File-Handling Questions and Answers:-

 Question 1:Write a program in C to create and store information in a text file.

Solution:

#include <stdio.h>

#include <stdlib.h>

int main()

{

    char str[1000];

    FILE *fptr;

    char fname[20] = "test.txt";

    printf("\n\n Create a file (test.txt) and input text :\n");

    printf("----------------------------------------------\n");

    fptr = fopen(fname, "w");

    if (fptr == NULL)

    {

        printf(" Error in opening file!");

        exit(1);

    }

    printf(" Input a sentence for the file : ");

    fgets(str, sizeof str, stdin);

    fprintf(fptr, "%s", str);

    fclose(fptr);

    printf("\n The file %s created successfully...!!\n\n", fname);

    return 0;

}

                    You can check the solution:- Check here


Question 2:Write a program in C to read an existing file.

Solution:

#include <stdio.h>

#include <stdlib.h>


void main()

{

FILE *fptr;

char fname[20];

char str;

    printf("\n\n Read an existing file :\n");

printf("------------------------------\n"); 

printf(" Input the filename to be opened : ");

scanf("%s",fname);

fptr = fopen (fname, "r");  

if (fptr == NULL)

{

printf(" File does not exist or cannot be opened.\n");

exit(0);

}

printf("\n The content of the file %s is  :\n",fname);

str = fgetc(fptr);

while (str != EOF)

{

printf ("%c", str);

str = fgetc(fptr);

}

fclose(fptr);

    printf("\n\n");

}

                    You can check the solution:- Check here


Question 3:Write a program in C to write multiple lines in a text file.

Solution:

#include <stdio.h>

int main ()

{

  FILE * fptr;

  int i,n;

  char str[100];

  char fname[20]="test.txt";

  char str1;

    printf("\n\n Write multiple lines in a text file and read the file :\n");

printf("------------------------------------------------------------\n");   

printf(" Input the number of lines to be written : ");

scanf("%d", &n);

printf("\n :: The lines are ::\n");

fptr = fopen (fname,"w"); 

for(i = 0; i < n+1;i++)

{

fgets(str, sizeof str, stdin);

fputs(str, fptr);

}

  fclose (fptr);

/*-------------- read the file -------------------------------------*/

fptr = fopen (fname, "r");  

printf("\n The content of the file %s is  :\n",fname);

str1 = fgetc(fptr);

while (str1 != EOF)

{

printf ("%c", str1);

str1 = fgetc(fptr);

}

    printf("\n\n");

    fclose (fptr);

    return 0;

}

                    You can check the solution:- Check here


Question 4:Write a program in C to count a number of words and characters in a file.

Solution:

#include <stdio.h>

#include <stdlib.h>

void main() 

    FILE *fptr; 

    char ch; 

    int wrd=1,charctr=1;

    char fname[20];

    printf("\n\n Count the number of words and characters in a file :\n");

printf("---------------------------------------------------------\n"); 

printf(" Input the filename to be opened : ");

scanf("%s",fname);    

    fptr=fopen(fname,"r"); 

    if(fptr==NULL) 

     { 

         printf(" File does not exist or can not be opened."); 

      } 

    else 

        { 

          ch=fgetc(fptr); 

          printf(" The content of the file %s are : ",fname); 

          while(ch!=EOF) 

            { 

                printf("%c",ch); 

                if(ch==' '||ch=='\n')

                    { 

                        wrd++; 

                    }

                    else

                    {

                        charctr++; 

                    }

                ch=fgetc(fptr); 

            }

        printf("\n The number of words in the  file %s are : %d\n",fname,wrd-2); 

        printf(" The number of characters in the  file %s are : %d\n\n",fname,charctr-1);         

        } 

    fclose(fptr); 

}

                    You can check the solution:- Check here


Question 5:Write a program in C to delete a specific line from a file.

Solution:

#include <stdio.h>

#include <string.h>


#define MAX 256


  int main() 

  {

        int lno, ctr = 0;

        char ch;

        FILE *fptr1, *fptr2;

char fname[MAX];

        char str[MAX], temp[] = "temp.txt";

printf("\n\n Delete a specific line from a file :\n");

printf("-----------------------------------------\n"); 

printf(" Input the file name to be opened : ");

scanf("%s",fname);

        fptr1 = fopen(fname, "r");

        if (!fptr1) 

{

                printf(" File not found or unable to open the input file!!\n");

                return 0;

        }

        fptr2 = fopen(temp, "w"); // open the temporary file in write mode 

        if (!fptr2) 

{

                printf("Unable to open a temporary file to write!!\n");

                fclose(fptr1);

                return 0;

        }

        printf(" Input the line you want to remove : ");

        scanf("%d", &lno);

lno++;

        // copy all contents to the temporary file except the specific line

        while (!feof(fptr1)) 

        {

            strcpy(str, "\0");

            fgets(str, MAX, fptr1);

            if (!feof(fptr1)) 

            {

                ctr++;

                /* skip the line at given line number */

                if (ctr != lno) 

                {

                    fprintf(fptr2, "%s", str);

                }

            }

        }

        fclose(fptr1);

        fclose(fptr2);

        remove(fname);   // remove the original file 

        rename(temp, fname);  // rename the temporary file to original name

/*------ Read the file ----------------*/

   fptr1=fopen(fname,"r"); 

            ch=fgetc(fptr1); 

          printf(" Now the content of the file %s is : \n",fname); 

          while(ch!=EOF) 

            { 

                printf("%c",ch); 

                 ch=fgetc(fptr1); 

            }

        fclose(fptr1);

/*------- End of reading ---------------*/

        return 0;

  } 

                    You can check the solution:- Check here


Question 6:Write a program in C to replace a specific line with another text in a file.

Solution:

#include <stdio.h>

#include <string.h>

#define MAX 256

  int main() 

  {

        FILE *fptr1, *fptr2;

        int lno, linectr = 0;

        char str[MAX],fname[MAX];        

        char newln[MAX], temp[] = "temp.txt";

printf("\n\n Replace a specific line in a text file with a new text :\n");

printf("-------------------------------------------------------------\n"); 

printf(" Input the file name to be opened : ");

        fgets(fname, MAX, stdin);

        fname[strlen(fname) - 1] = '\0';

        fptr1 = fopen(fname, "r");

        if (!fptr1) 

        {

                printf("Unable to open the input file!!\n");

                return 0;

        }

        fptr2 = fopen(temp, "w");

        if (!fptr2) 

        {

                printf("Unable to open a temporary file to write!!\n");

                fclose(fptr1);

                return 0;

        }

        /* get the new line from the user */

        printf(" Input the content of the new line : ");

        fgets(newln, MAX, stdin);

        /* get the line number to delete the specific line */

        printf(" Input the line no you want to replace : ");

        scanf("%d", &lno);

        lno++;

         // copy all contents to the temporary file other except specific line

        while (!feof(fptr1)) 

        {

            strcpy(str, "\0");

            fgets(str, MAX, fptr1);

            if (!feof(fptr1)) 

            {

                linectr++;

                if (linectr != lno) 

                    {

                        fprintf(fptr2, "%s", str);

                    } 

                    else 

                    {

                        fprintf(fptr2, "%s", newln);

                    }

                }

        }

        fclose(fptr1);

        fclose(fptr2);

        remove(fname);

        rename(temp, fname);

        printf(" Replacement did successfully..!! \n");

        return 0;

  }

                    You can check the solution:- Check here


Question 7: Write a program in C to append multiple lines at the end of a text file.

Solution:

#include <stdio.h>

int main ()

{

  FILE * fptr;

  int i,n;

  char str[100];

  char fname[20];

  char str1;

  

printf("\n\n Append multiple lines at the end of a text file :\n");

printf("------------------------------------------------------\n"); 

printf(" Input the file name to be opened : ");

scanf("%s",fname);

    fptr = fopen(fname, "a"); 

    printf(" Input the number of lines to be written : ");

    scanf("%d", &n);

    printf(" The lines are : \n");  

    for(i = 0; i < n+1;i++)

    {

    fgets(str, sizeof str, stdin);

    fputs(str, fptr);

  }

  fclose (fptr);

//----- Read the file after appended ------- 

fptr = fopen (fname, "r");  

printf("\n The content of the file %s is  :\n",fname);

str1 = fgetc(fptr);

while (str1 != EOF)

{

printf ("%c", str1);

str1 = fgetc(fptr);

}

    printf("\n\n");

    fclose (fptr);

//------- End of reading ------------------

  return 0;

}

                    You can check the solution:- Check here


Question 8:Write a program in C to copy a file in another name.

Solution:

#include <stdio.h>

#include <stdlib.h>

void main()

{

FILE *fptr1, *fptr2;

char ch, fname1[20], fname2[20];


printf("\n\n Copy a file in another name :\n");

printf("----------------------------------\n"); 


printf(" Input the source file name : ");

scanf("%s",fname1);


fptr1=fopen(fname1, "r");

if(fptr1==NULL)

{

printf(" File does not found or error in opening.!!");

exit(1);

}

printf(" Input the new file name : ");

scanf("%s",fname2);

fptr2=fopen(fname2, "w");

if(fptr2==NULL)

{

printf(" File does not found or error in opening.!!");

fclose(fptr1);

exit(2);

}

while(1)

{

ch=fgetc(fptr1);

if(ch==EOF)

{

break;

}

else

{

fputc(ch, fptr2);

}

}

printf(" The file %s  copied successfully in the file %s. \n\n",fname1,fname2);

fclose(fptr1);

fclose(fptr2);

getchar();

}

                    You can check the solution:- Check here


Question 9:Write a program in C to merge two files and write it in a new file

Solution:

#include <stdio.h>

#include <stdlib.h>

void main()

{

FILE *fold1, *fold2, *fnew;

char ch, fname1[20], fname2[20], fname3[30];

printf("\n\n Merge two files and write it in a new file :\n");

printf("-------------------------------------------------\n"); 

printf(" Input the 1st file name : ");

scanf("%s",fname1);

printf(" Input the 2nd file name : ");

scanf("%s",fname2);

printf(" Input the new file name where to merge the above two files : ");

scanf("%s",fname3);

fold1=fopen(fname1, "r");

fold2=fopen(fname2, "r");

if(fold1==NULL || fold2==NULL)

{

              //perror("Error Message ");

printf(" File does not exist or error in opening...!!\n");

exit(EXIT_FAILURE);

}

fnew=fopen(fname3, "w");

if(fnew==NULL)

{

            //perror("Error Message ");

printf(" File does not exist or error in opening...!!\n");

exit(EXIT_FAILURE);

}

while((ch=fgetc(fold1))!=EOF)

{

fputc(ch, fnew);

}

while((ch=fgetc(fold2))!=EOF)

{

fputc(ch, fnew);

}

printf(" The two files merged into %s file successfully..!!\n\n", fname3);

fclose(fold1);

fclose(fold2);

fclose(fnew);

}

                    You can check the solution:- Check here


Question 10:Write a program in C to encrypt a text file.

Solution:

#include <stdio.h>

#include <stdlib.h>


void main()

{

char fname[20], ch;

FILE *fpts, *fptt;

printf("\n\n Encrypt a text file :\n");

printf("--------------------------\n"); 

printf(" Input the name of file to encrypt : ");

scanf("%s",fname);


fpts=fopen(fname, "r");

if(fpts==NULL)

{

printf(" File does not exists or error in opening..!!");

exit(1);

}

fptt=fopen("temp.txt", "w");

if(fptt==NULL)

{

printf(" Error in creation of file temp.txt ..!!");

fclose(fpts);

exit(2);

}

while(1)

{

ch=fgetc(fpts);

if(ch==EOF)

{

break;

}

else

{

ch=ch+100;

fputc(ch, fptt);

}

}

fclose(fpts);

fclose(fptt);

fpts=fopen(fname, "w");

if(fpts==NULL)

{

printf(" File does not exists or error in opening..!!");

exit(3);

}

fptt=fopen("temp.txt", "r");

if(fptt==NULL)

{

printf(" File does not exists or error in opening..!!");

fclose(fpts);

exit(4);

}

while(1)

{

ch=fgetc(fptt);

if(ch==EOF)

{

break;

}

else

{

fputc(ch, fpts);

}

}

printf(" File %s successfully encrypted ..!!\n\n", fname);

fclose(fpts);

fclose(fptt);

}

                    You can check the solution:- Check here


Question 11:Write a program in C to remove a file from the disk.

Solution:

#include <stdio.h>

void main()

{

int status;

char fname[20];

printf("\n\n Remove a file from the disk :\n");

printf("----------------------------------\n"); 

printf(" Input the name of file to delete : ");

scanf("%s",fname);

status=remove(fname);

if(status==0)

{

printf(" The file %s is deleted successfully..!!\n\n",fname);

}

else

{

printf(" Unable to delete file %s\n\n",fname);

}

}

                    You can check the solution:- Check here


**Important**


Question 1: Write a program to read 20 integers using command line arguments and store them into a file Numbers.txt in the current working path. Later by reading from that file separate them into two different files odd-numbers.txt and even-numbers.txt such that odd numbers are copied to odd-numbers.txt and even numbers are copied to even-numbers.txt files respectively in the same current working path.

Sample Input:

D:\….> Numbers 12 11 13 18 119 122 18 24 25 39 37 42 45 50 55 56 58 60 75 77

Sample Output:

                File: Numbers.txt: 12 11 13 18 119 122 18 24 25 39 37 42 45 50 55 56 58 60 76 77
                File: odd.txt: 11 13 119 25 39 37 45 55 77
                File: even.txt: 12 18 122 18 24 42 50 56 58 60 76

 Solution:
            #include <stdio.h>
            #include <stdlib.h>
            /* Function declarations */
            int isEven(const int NUM);
            int main()
            {
                /* File pointer to hold reference to different files */
                FILE * fPtrIn,
                 * fPtrEven, 
                 * fPtrOdd;
                    int num, success;
                     /* Open all files to perform read/write.*/
                    fPtrIn   = fopen("numbers.txt", "r");
                    fPtrEven = fopen("even-numbers.txt" , "w");
                    fPtrOdd  = fopen("odd-numbers.txt"  , "w");
                    /* fopen() return NULL if unable to open file in given mode. */
                    if(fPtrIn == NULL || fPtrEven == NULL || fPtrOdd == NULL)
                    {
                            /* Unable to open file hence exit */
                                printf("Unable to open file.\n");
                    printf("Please check whether file exists and you have read/write privilege.\n");
                    exit(EXIT_FAILURE);
                    }
                /* File open success message */
                printf("File opened successfully. Reading integers from file. \n\n");
                // Read an integer and store read status in success.
                while (fscanf(fPtrIn, "%d", &num) != -1)
                {
                    /* Write prime, even and odd numbers to different files.*/
                    if (isEven(num))
                    fprintf(fPtrEven, "%d\n", num);
                    else
                    fprintf(fPtrOdd, "%d\n", num);
                }
                /* Done with all files, hence close all. */
                fclose(fPtrIn);
                fclose(fPtrEven);
                    fclose(fPtrOdd);
                printf("Data written to files successfully.");
               return 0;
            }
        /*Check whether a given number is even or not. The function return 1 if given number is odd, otherwise return 0.*/
int isEven(const int NUM)
            {
               return !(NUM & 1);
            }
Code

Code

Input
ODD-NUMBERS

EVEN-NUMBERS

Question 2: Design a program in C to accept the details of N students such as Name, USN and Semester number from the user. Store these details to a file Students.txt in the format given below in the path D:\UniversityData.

        Ashutosh Rana                   PV-101201113              2
        Bhairavi Singh                    PV-101201153             3
        K Chandrashekar               PV-101201163             5
        …..and so on

Solution:

#include <stdio.h>

#include <stdlib.h>

int main() {

char name[50];

char usn[10];

int usn_number;

int sem,i,n;

printf("Enter number of students: ");

scanf("%d",&n);

FILE *fptr;

fptr=(fopen("D:\\UniversityData.txt","w"));

if(fptr==NULL) {

printf("Error!");

exit(1);

}

for (i=0;i<n;++i) {

printf("For student%d\nEnter name: ",i+1);

scanf("%s",name);

printf("Enter University no.(After character give space): ");

scanf("%s%d",&usn,&usn_number);

printf("Enter Semester: ");

scanf("%d",&sem);

fprintf(fptr,"\n %s \t%s-%d \t%d \n",name,usn,usn_number,sem);

}

fclose(fptr);

return 0;

}


Note: Ensure that the folder ‘UniversityData’ is created in the D-drive and each field is separated by a tab space ie between name and usn or usn and semno.


Code



Input Format
Input Successfully saved in D: drive. 

Output


Question 3: Write a program in C to create a file and copy its contents to another file such that there is no space between words in copied file. Display the content of the newly copied file to the output screen.

Solution:

        #include <stdio.h>
        #include <stdlib.h>
        int main()
        {
                FILE *fptr1, *fptr2;
                char ch, fname1[20], fname2[20];
                printf("\n\n Copy a file in another name :\n");
                printf("----------------------------------\n");
                printf(" Input the source file name : ");
                scanf("%s", fname1);
                fptr1 = fopen(fname1, "r");
                printf(" Input the new file name : ");
                scanf("%s", fname2);
                fptr2 = fopen(fname2, "w");
                if (fptr1 == NULL)
                {
                    printf("Some problem in opening the file");
                    exit(0);
                }
                else
                {
                    while ((ch = fgetc(fptr1)) != EOF)
                    {
                        if (ch == ' ' || ch == '\n')
                        {    
                        }
                        else
                           {
                                fprintf(fptr2, "%c", ch);
                           }
                    }
            }
            fclose(fptr1);
            fclose(fptr2);
            return 0;
        }
Code
Process
Input File

Output File


Please hit the bell icon and Subscribe to "Coding With Fun" (showing in the right corner➡) for receiving our exclusive content.

Post a Comment

2 Comments

  1. You haven't used the command line arguments in question1 of important........ And according to question you have to use it in program.. :)

    ReplyDelete

If you are a good learner please leave a challenging question on comment box for us when you visited this website ( Coding with Fun).