Ask Question

Write two functions, which read/write an array of records to/from a file. Write driver code to test the two functions. The driver code and the test output must show clearly that the file input and output work correctly

+3
Answers (1)
  1. 1 May, 00:48
    0
    fwrite

    / / C program for writing

    / / struct to file

    #include

    #include

    #include

    / / a struct to read and write

    struct person

    {

    int id;

    char fname[20];

    char lname[20];

    };

    int main ()

    {

    FILE * outfile;

    / / open file for writing

    outfile = fopen ("person. dat", "w");

    if (outfile = = NULL)

    {

    fprintf (stderr, "/nError opend file/n");

    exit (1);

    }

    struct person input1 = {1, "rohan", "sharma"};

    struct person input2 = {2, "mahendra", "dhoni"};

    / / write struct to file

    fwrite (&input1, sizeof (struct person), 1, outfile);

    fwrite (&input2, sizeof (struct person), 1, outfile);

    if (fwrite! = 0)

    printf ("contents to file written successfully!/n");

    else

    printf ("error writing file!/n");

    / / close file

    fclose (outfile);

    return 0;

    }

    fread

    / / C program for reading

    / / struct from a file

    #include

    #include

    / / struct person with 3 fields

    struct person

    {

    int id;

    char fname[20];

    char lname[20];

    };

    / / Driver program

    int main ()

    {

    FILE * infile;

    struct person input;

    / / Open person. dat for reading

    infile = fopen ("person. dat", "r");

    if (infile = = NULL)

    {

    fprintf (stderr, "/nError opening file/n");

    exit (1);

    }

    / / read file contents till end of file

    while (fread (&input, sizeof (struct person), 1, infile))

    printf ("id = %d name = %s %s/n", input. id,

    input. fname, input. lname);

    / / close file

    fclose (infile);

    return 0;

    }
Know the Answer?
Not Sure About the Answer?
Find an answer to your question 👍 “Write two functions, which read/write an array of records to/from a file. Write driver code to test the two functions. The driver code and ...” in 📗 Computers & Technology if the answers seem to be not correct or there’s no answer. Try a smart search to find answers to similar questions.
Search for Other Answers