WalzoneInterview Prep
πŸ“ž Interviewing soon? Practice with a realistic AI mock phone interview β€” it calls you, then scores you. First 15 min FREE β†’

C Β· Intermediate Β· question 39 of 100

What is a file I/O operation, and how do you perform them in C? Explain the modes for opening a file.?

πŸ“• Buy this interview preparation book: 100 C questions & answers β€” PDF + EPUB for $5

File I/O (input/output) operations in C refer to the ability to read data from and write data to files on a disk or other storage device. File I/O is essential for many types of programs, including those that handle large amounts of data, such as databases and media players.

In C, file I/O operations are performed using the standard I/O library, which provides a set of functions for opening, reading from, writing to, and closing files. The basic steps for performing file I/O in C are as follows:

Open the file using the fopen() function. This function takes two arguments: the name of the file and the mode in which to open it.

Perform the desired read or write operation using functions such as fread(), fwrite(), fscanf(), or fprintf(), depending on the data type and format.

Close the file using the fclose() function when the operations are complete.

The modes for opening a file in C are:

Here is an example of opening a file for writing and writing data to it:

    #include <stdio.h>
    
    int main() {
        FILE *fp;
        char str[] = "This is a test string.";
        fp = fopen("testfile.txt", "w");
        if (fp == NULL) {
            printf("Error opening file.");
            return 1;
        }
        fwrite(str, sizeof(char), sizeof(str), fp);
        fclose(fp);
        return 0;
    }

In this example, the fopen() function is used to open a file named "testfile.txt" in write mode. The fwrite() function is then used to write a test string to the file, and the fclose() function is used to close the file.

It is important to note that file I/O operations can fail due to various reasons, such as the file not existing, insufficient permissions, or disk errors. It is therefore important to check the return value of file I/O functions and handle errors appropriately.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic C interview β€” then scores it.
πŸ“ž Practice C β€” free 15 min
πŸ“• Buy this interview preparation book: 100 C questions & answers β€” PDF + EPUB for $5

All 100 C questions Β· All topics