Computer Scientists are Pretty Pessimistic

Showing posts with label FILE. Show all posts
Showing posts with label FILE. Show all posts

Saturday, 13 February 2016

How to write FILE in C ?

Solution : :

#include <stdio.h>
int main ()
{
    FILE *fp;
    char name[30],country[30],mob[20];
    int id;
    printf("Enter your name: ");
    gets(name);
    strcat(name,"\n");
    printf("\nEnter country name: ");
    gets(country);
    strcat(country,"\n");
    printf("\nEnter mobile number: ");
    gets(mob);
    strcat(mob,"\n");
    fflush(stdin);
    printf("\nEnter your id: ");
    scanf("%d",&id);

    if((fp=fopen("myfile.txt","w"))!=NULL)
        printf("File open successfully\n");
    else
        { printf("ERROR in file creation\n"); return 0;}

    if(fputs(name,fp)==EOF)
    {
        printf("\n Error occured in writing name on file.");
        return 0;
    }
    else
        printf("\nYour name's been written successfully.");
    if(fputs(country,fp)==EOF)
    {
        printf("\n Error occured in writing country name on file.");
        return 0;
    }
    else
        printf("\nYour country name's been written successfully.");

    if(fputs(mob,fp)==EOF)
    {
        printf("\n Error occured in writing mobile number on file.");
        return 0;
    }
    else
        printf("\nYour mobile number has been written successfully.");
    if(fprintf(fp,"%d",id)==EOF)
    {
        printf("\n Error occured in writing your id on file.");
        return 0;
    }
    else
        printf("\nYour id number has been written successfully.");

    if(fclose(fp)==EOF)
        { printf("\nERROR in file closing"); return 0;}
    else
        printf("\nSuccessfully close your file");

    return 0;

}

How to read a FILE in C ?

Solution : :

#include <stdio.h>
int main ()
{
    FILE *fp;
    char strF[50];
    int idF;
    if((fp=fopen("myfile.txt","r"))!=NULL)
        printf("Successfully file open");
    else
    {
        printf("\nError in file opening");
        return 0;
    }
    if(fgets(strF,50,fp) != NULL)
        printf("\n\n Your name: %s",strF);
    else
        printf("\n\n Problem in reading from file.");
    if(fgets(strF,50,fp) != NULL)
        printf("\n\n Your country is: %s",strF);
    else
        printf(" Problem in reading from file.");
    if(fgets(strF,50,fp) != NULL)
        printf("\n\n Your mob number is: %s",strF);
    else
        printf(" Problem in reading from file.");
    if((fscanf(fp,"%d",&idF))<0)
    {
        printf("\n Error occured reading the numbers.");
        return 0;
    }
    else
        printf("\n\n Your id is %d",idF);
    if(fclose(fp)==EOF)
    { printf("Error in closing file\n"); return 0; }
    else
        printf("\n\nSuccessfully close\n");
}