Problem Solving Through C (BCA) 1st Sem Previous Year Solved Question Paper 2022

Practice Mode:
16.

How to create, open and close a file in a C program ? Discuss various functions used to write into a file.

Explanation

Create, open, and close files in a program using functions from the standard input/output library. The key functions for file operations are fopen(), fclose(), and various functions for reading and writing to files

  1. Create a File: To create a new file, you can use the fopen() function with the "w" mode (write mode). If the file already exists, it will be truncated; if it doesn't exist, a new file will be created.

#include <stdio.h>


int main() {

FILE *file;

file = fopen("example.txt", "w");


 if (file == NULL) {

printf("Failed to create/open the file.\n");

return 1;

}


 // Perform file operations here


 fclose(file); // Close the file

return 0;

}


2. Open a File: To open an existing file for reading or writing, you can use fopen() with different modes such as "r" (read), "w" (write), "a" (append), and more.

FILE *file;

file = fopen("existing_file.txt", "r"); // Open for reading


if (file == NULL) {

printf("Failed to open the file.\n");

return 1;

}


// Perform file operations here


fclose(file); // Close the file

Close a File: Always remember to close a file using the fclose() function when you're done with it. This ensures that any changes are saved, and resources are released.

FILE *file;

file = fopen("example.txt", "w");


if (file == NULL) {

printf("Failed to create/open the file.\n");

return 1;

}


// Perform file operations here


fclose(file); // Close the file

  1. Writing to a File: To write data to a file, you can use functions like fprintf(), fputc(), and fputs(). Here's an example using fprintf() to write text to a file.

FILE *file;

file = fopen("output.txt", "w");


if (file == NULL) {

printf("Failed to create/open the file.\n");

return 1;

}

fprintf(file, "Hello, this is some text.\n");

fclose(file); // Close the file


Other functions like ‘fputc()’ and ‘fputs()’ can be used for character-wise and string-wise output, respectively.