File stream
File stream A file stream is a sequence of bytes that is read or written from a file. It is a mechanism that allows you to read or write data from a file wi...
File stream A file stream is a sequence of bytes that is read or written from a file. It is a mechanism that allows you to read or write data from a file wi...
File stream
A file stream is a sequence of bytes that is read or written from a file. It is a mechanism that allows you to read or write data from a file without having to read the entire file into memory at once. Instead, the file stream is opened and accessed using a pointer, which is a variable that points to the first byte of the file.
Example:
c
#include <stdio.h>
#include <stdlib.h>
int main() {
// Open a file stream for reading
FILE *fp = fopen("myfile.txt", "r");
// Check if the file is open
if (fp == NULL) {
perror("Error opening file");
return 1;
}
// Get the file size
long int file_size = filesize(fp);
// Read the file contents
char *data = malloc(file_size + 1);
fread(data, 1, file_size, fp);
// Close the file stream
fclose(fp);
// Print the contents of the file
printf("File contents: %s\n", data);
// Free the allocated memory
free(data);
return 0;
}
Explanation:
The fopen function opens a file stream for reading.
The filesize function determines the size of the file.
The fread function reads the contents of the file into the data variable.
The fclose function closes the file stream.
The malloc function is used to allocate memory for the file contents.
The free function is used to release the allocated memory.
Benefits of using file streams:
Efficiency: Reading and writing data from a file is much faster than reading and writing data from memory.
Memory portability: File streams can be opened on different machines with the same file pointer.
Convenience: File streams provide a convenient way to read and write data from a file