Concept
What is 22?
ComputerScienceOne / Opening Files
"22. File I/O C provides several functions to manipulate and process files. Like other I/O functions, these are all defined in the standard input/output library, stdio.h . Writing binary or plaintext data is determined by which functions you use. Whether or not a file input/output stream is buffered or unbuffered is determined by the system configuration. There are some ways in which this can be changed, but we will not cover them in detail. 22.1. Opening Files Files are represented in C by a FILE * pointer type defined in the standard input/output library. As a pointer, it essentially points to the file stored in memory. To open a file, you use the fopen() function (short for f ile open ) which takes two arguments and returns a FILE * pointer: FILE *fopen(const char *path, const char *mode); The first argument is the file path/name that you want to open for processing. The second argument is a string representing the “mode” that you want to open the file in. There are several supported modes, but the two we will be interested in are reading, in which case you pass it \"r\" and writing in which case you pass it \"w\" . The path can be an absolute path, relative path, or may be omitted if the file is in the current working directory. 1 //open a file for reading (input): 2 FILE *input = fopen(\"/user/apps/data.txt\", \"r\"); 3 //open a file for writing (output): 4 FILE *output = fopen(\"./results.txt\", \"w\"); 5 6 if(input == NULL) { 7 fprintf(stderr, \"Unable to open input file\"); 8 exit(1); 9 } 10 11 if(output == NULL) { 335"
Related Ideas
- How do you open and validate files in PHP?ComputerScienceOne · Opening Files
- How do fread and fwrite read and write binary data?ComputerScienceOne · Binary Files
- How do fprintf() and fscanf() read from and write to plaintext files?ComputerScienceOne · Plaintext Files
- How does PHP handle file input and output?ComputerScienceOne · Opening Files
- How do file names, extensions, and working directories affect file paths?ComputerScienceOne · Paths
- What types of errors can occur when processing files?ComputerScienceOne · Error Handling
- How do buffered and unbuffered file input/output differ?ComputerScienceOne · Buffered and Unbuffered
- How can you read a text file one line at a time?ComputerScienceOne · Binary Files