C Create Files
Introduction to File Handling in C
File handling is a crucial aspect of programming that allows you to store data persistently on storage devices. In C, file operations are performed using functions from the stdio.h header file, which provides a standardized way to work with files across different platforms.
File handling enables programs to:
- Store data permanently beyond program execution
- Read configuration files and data inputs
- Create logs and output reports
- Exchange data between different programs
File Streams and FILE Pointer
In C, files are accessed through file streams. A file stream is an abstraction that represents a connection between your program and a file. The FILE structure (defined in stdio.h) contains information about the file and its current state.
Key concepts:
- FILE pointer: A pointer to a FILE structure that represents an open file
- Stream: A sequential flow of bytes between program and file
- Buffer: Temporary storage area that improves I/O efficiency
Opening Files with fopen()
The fopen() function opens a file and returns a FILE pointer. It takes two parameters:
- filename: The name of the file to open (including path if needed)
- mode: Specifies how the file should be opened
FILE *fopen(const char *filename, const char *mode);
File Opening Modes
Mode | Description | File Position |
---|---|---|
"r" | Open for reading (file must exist) | Beginning |
"w" | Open for writing (creates or truncates) | Beginning |
"a" | Open for appending (creates if doesn't exist) | End |
"r+" | Open for reading and writing (file must exist) | Beginning |
"w+" | Open for reading and writing (creates or truncates) | Beginning |
"a+" | Open for reading and appending (creates if doesn't exist) | End for writing, beginning for reading |
Basic File Creation Example
#include <stdio.h>
int main(void) {
FILE *file = fopen("example.txt", "w");
if (file == NULL) {
perror("fopen");
return 1;
}
printf("File created successfully.\n");
if (fclose(file) != 0) {
perror("fclose");
return 1;
}
return 0;
}
File created successfully.
Writing to a New File
After creating a file, write data using fprintf(), fputs(), or fwrite() depending on your needs.
#include <stdio.h>
int main(void) {
FILE *file = fopen("report.txt", "w");
if (!file) { perror("fopen"); return 1; }
fprintf(file, "Name,Score\n");
fprintf(file, "Alice,95\n");
fputs("Bob,88\n", file);
if (fclose(file) != 0) { perror("fclose"); return 1; }
printf("Wrote report.txt\n");
return 0;
}
Wrote report.txt
Checking File Existence Before Creation
#include <stdio.h>
int main(void) {
char filename[100];
printf("Enter filename to create: ");
if (scanf("%99s", filename) != 1) {
printf("Input error.\n");
return 1;
}
FILE *file = fopen(filename, "rb"); // check existence (binary read)
if (file != NULL) {
fclose(file);
printf("File already exists. Overwrite? (y/n): ");
char choice;
if (scanf(" %c", &choice) != 1 || (choice != 'y' && choice != 'Y')) {
printf("File creation cancelled.\n");
return 0;
}
}
file = fopen(filename, "wb"); // create/truncate in binary
if (file == NULL) { perror("fopen"); return 1; }
printf("File '%s' created successfully.\n", filename);
if (fclose(file) != 0) { perror("fclose"); return 1; }
return 0;
}
Binary vs Text Files
C distinguishes between text files and binary files:
- Text files: Store data as human-readable characters. Use modes like "r", "w", "a" (or with 't' on some systems).
- Binary files: Store data in raw binary format. Use modes like "rb", "wb", "ab".
The main difference is how newlines are handled and whether character translation occurs on the host platform.
#include <stdio.h>
int main(void) {
FILE *textFile = fopen("textfile.txt", "w");
FILE *binaryFile = fopen("binaryfile.bin", "wb");
if (textFile) { fputs("Line 1\nLine 2\n", textFile); }
if (binaryFile) {
unsigned char data[3] = {0xDE, 0xAD, 0xBE};
fwrite(data, 1, sizeof data, binaryFile);
}
if (textFile && fclose(textFile) != 0) { perror("fclose text"); }
if (binaryFile && fclose(binaryFile) != 0) { perror("fclose bin"); }
if (textFile && binaryFile)
printf("Both text and binary files created successfully.\n");
else
printf("Error creating one or more files.\n");
return 0;
}
Both text and binary files created successfully.