C How to Open a File for Reading
If you've written the C helloworld program before, you already know basic file I/O in C:
/* A simple how-do-you-do world in C. */ #include <stdlib.h> // Import IO functions. #include <stdio.h> int main() { // This printf is where all the file IO magic happens! // How exciting! printf("Hullo, world!\n"); return EXIT_SUCCESS; } File handling is one of the most important parts of programming. In C, we utilise a structure pointer of a file type to declare a file:
FILE *fp; C provides a number of build-in function to perform bones file operations:
-
fopen()- create a new file or open a existing file -
fclose()- shut a file -
getc()- reads a character from a file -
putc()- writes a character to a file -
fscanf()- reads a set of information from a file -
fprintf()- writes a set of data to a file -
getw()- reads a integer from a file -
putw()- writes a integer to a file -
fseek()- set the position to desire indicate -
ftell()- gives electric current position in the file -
rewind()- set the position to the beginning point
Opening a file
The fopen() office is used to create a file or open an existing file:
fp = fopen(const char filename,const char mode); At that place are many modes for opening a file:
-
r- open up a file in read mode -
westward- opens or create a text file in write mode -
a- opens a file in suspend mode -
r+- opens a file in both read and write mode -
a+- opens a file in both read and write mode -
w+- opens a file in both read and write mode
Here's an example of reading data from a file and writing to it:
#include<stdio.h> #include<conio.h> main() { FILE *fp; char ch; fp = fopen("hello.txt", "west"); printf("Enter data"); while( (ch = getchar()) != EOF) { putc(ch,fp); } fclose(fp); fp = fopen("hello.txt", "r"); while( (ch = getc(fp)! = EOF) printf("%c",ch); fclose(fp); } Now you might be thinking, "This merely prints text to the screen. How is this file IO?"
The answer isn't obvious at start, and needs some agreement about the UNIX arrangement. In a UNIX system, everything is treated as a file, pregnant you can read from and write to it.
This ways that your printer tin exist bathetic as a file since all you do with a printer is write with it. It is likewise useful to think of these files as streams, since equally yous'll meet later, you can redirect them with the crush.
And then how does this relate to helloworld and file IO?
When you call printf, y'all are really just writing to a special file called stdout, brusk for standard output . stdout represents the standard output as decided past your shell, which is usually the concluding. This explains why it printed to your screen.
There are two other streams (i.e. files) that are bachelor to you with effort, stdin and stderr. stdin represents the standard input , which your vanquish normally attaches to the keyboard. stderr represents the standard fault output, which your vanquish usually attaches to the terminal.
Rudimentary File IO, or How I Learned to Lay Pipes
Enough theory, allow's get down to business by writing some code! The easiest way to write to a file is to redirect the output stream using the output redirect tool, >.
If you want to append, you tin can utilize >>:
# This will output to the screen... ./helloworld # ...simply this will write to a file! ./helloworld > howdy.txt The contents of hello.txt will, not surprisingly, be
Hello, world! Say we have another programme called greet, similar to helloworld, that greets you with a given proper noun:
#include <stdio.h> #include <stdlib.h> int main() { // Initialize an assortment to hold the proper name. char name[20]; // Read a string and save it to name. scanf("%s", name); // Print the greeting. printf("Hello, %due south!", name); return EXIT_SUCCESS; } Instead of reading from the keyboard, nosotros can redirect stdin to read from a file using the < tool:
# Write a file containing a name. repeat Kamala > proper name.txt # This will read the proper name from the file and print out the greeting to the screen. ./greet < proper noun.txt # ==> Hello, Kamala! # If you wanted to as well write the greeting to a file, yous could do and then using ">". Note: these redirection operators are in fustigate and similar shells.
The Real Deal
The above methods only worked for the almost basic of cases. If you wanted to do bigger and better things, you will probably desire to work with files from within C instead of through the shell.
To achieve this, you will use a role chosen fopen. This part takes two string parameters, the first being the file name and the 2d being the mode.
The way are basically permissions, so r for read, w for write, a for append. You tin besides combine them, so rw would hateful you lot could read and write to the file. There are more modes, but these are the nearly unremarkably used.
Afterward yous have a FILE arrow, yous can employ basically the same IO commands you would've used, except that you have to prefix them with f and the starting time argument will be the file pointer. For example, printf'due south file version is fprintf.
Here's a programme called greetings that reads a from a file containing a list of names and write the greetings to another file:
#include <stdio.h> #include <stdlib.h> int master() { // Create file pointers. FILE *names = fopen("names.txt", "r"); FILE *greet = fopen("greet.txt", "w"); // Bank check that everything is OK. if (!names || !greet) { fprintf(stderr, "File opening failed!\n"); render EXIT_FAILURE; } // Greetings time! char proper name[twenty]; // Basically go along on reading untill there's cipher left. while (fscanf(names, "%southward\northward", name) > 0) { fprintf(greet, "Hi, %s!\northward", proper name); } // When reached the end, print a message to the terminal to inform the user. if (feof(names)) { printf("Greetings are done!\due north"); } return EXIT_SUCCESS; } Suppose names.txt contains the following:
Kamala Logan Carol Then after running greetings the file greet.txt will contain:
Hello, Kamala! Howdy, Logan! How-do-you-do, Carol! Acquire to lawmaking for complimentary. freeCodeCamp'due south open source curriculum has helped more than 40,000 people become jobs as developers. Get started
Source: https://www.freecodecamp.org/news/file-handling-in-c-how-to-open-close-and-write-to-files/
0 Response to "C How to Open a File for Reading"
Post a Comment