Rename the Attached as Thinker.txt and Read the Data Only, Using Scanf Command.
If you've written the C helloworld program before, y'all already know basic file I/O in C:
/* A uncomplicated hello 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("Hello, globe!\northward"); return EXIT_SUCCESS; } File handling is one of the nearly important parts of programming. In C, we use a structure arrow of a file blazon to declare a file:
FILE *fp; C provides a number of build-in function to perform basic file operations:
-
fopen()- create a new file or open a existing file -
fclose()- close a file -
getc()- reads a character from a file -
putc()- writes a character to a file -
fscanf()- reads a ready of data 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 point -
ftell()- gives current position in the file -
rewind()- prepare the position to the beginning point
Opening a file
The fopen() part is used to create a file or open an existing file:
fp = fopen(const char filename,const char mode); There are many modes for opening a file:
-
r- open a file in read mode -
westward- opens or create a text file in write mode -
a- opens a file in suspend manner -
r+- opens a file in both read and write style -
a+- opens a file in both read and write manner -
due west+- opens a file in both read and write mode
Hither'due south an instance of reading data from a file and writing to information technology:
#include<stdio.h> #include<conio.h> principal() { FILE *fp; char ch; fp = fopen("howdy.txt", "w"); printf("Enter data"); while( (ch = getchar()) != EOF) { putc(ch,fp); } fclose(fp); fp = fopen("howdy.txt", "r"); while( (ch = getc(fp)! = EOF) printf("%c",ch); fclose(fp); } At present yous might be thinking, "This just prints text to the screen. How is this file IO?"
The answer isn't obvious at first, and needs some understanding virtually the UNIX system. In a UNIX system, everything is treated equally a file, pregnant you lot tin can read from and write to it.
This means that your printer tin can be abstracted as a file since all yous do with a printer is write with it. It is also useful to think of these files equally streams, since as yous'll see later, you tin redirect them with the shell.
And so how does this relate to helloworld and file IO?
When you phone call printf, you lot are really just writing to a special file called stdout, short for standard output . stdout represents the standard output as decided past your vanquish, which is usually the last. This explains why it printed to your screen.
At that place are ii other streams (i.e. files) that are bachelor to you with effort, stdin and stderr. stdin represents the standard input , which your beat out usually attaches to the keyboard. stderr represents the standard mistake output, which your shell usually attaches to the terminal.
Rudimentary File IO, or How I Learned to Lay Pipes
Enough theory, let'southward get down to business concern 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 employ >>:
# This volition output to the screen... ./helloworld # ...but this volition write to a file! ./helloworld > howdy.txt The contents of hello.txt volition, not surprisingly, be
Hi, world! Say nosotros have another program called greet, similar to helloworld, that greets you with a given name:
#include <stdio.h> #include <stdlib.h> int main() { // Initialize an assortment to hold the name. char name[twenty]; // Read a string and salve it to name. scanf("%south", proper noun); // Print the greeting. printf("Hello, %south!", name); return EXIT_SUCCESS; } Instead of reading from the keyboard, we can redirect stdin to read from a file using the < tool:
# Write a file containing a name. echo Kamala > proper name.txt # This will read the proper noun from the file and print out the greeting to the screen. ./greet < proper name.txt # ==> Hello, Kamala! # If yous wanted to also write the greeting to a file, you could practice so using ">". Note: these redirection operators are in bash and similar shells.
The Real Bargain
The in a higher place methods only worked for the well-nigh basic of cases. If you wanted to practise bigger and better things, you lot volition probably want to work with files from within C instead of through the vanquish.
To accomplish this, you lot will use a function called fopen. This function takes 2 string parameters, the starting time being the file name and the second being the style.
The mode are basically permissions, so r for read, westward for write, a for suspend. You lot can also combine them, so rw would mean you could read and write to the file. There are more modes, but these are the nigh unremarkably used.
After you have a FILE pointer, you tin utilise basically the same IO commands y'all would've used, except that you accept to prefix them with f and the commencement statement will exist the file pointer. For example, printf'due south file version is fprintf.
Here'southward 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"); // Cheque that everything is OK. if (!names || !greet) { fprintf(stderr, "File opening failed!\due north"); return EXIT_FAILURE; } // Greetings time! char name[20]; // Basically go along on reading untill there's nix left. while (fscanf(names, "%s\n", proper name) > 0) { fprintf(greet, "Howdy, %south!\north", name); } // When reached the cease, impress a message to the concluding to inform the user. if (feof(names)) { printf("Greetings are washed!\n"); } return EXIT_SUCCESS; } Suppose names.txt contains the post-obit:
Kamala Logan Carol Then after running greetings the file greet.txt volition contain:
Hullo, Kamala! Hello, Logan! Hullo, Carol! Acquire to code for free. freeCodeCamp's open source curriculum has helped more 40,000 people get jobs as developers. Become started
Source: https://www.freecodecamp.org/news/file-handling-in-c-how-to-open-close-and-write-to-files/
Belum ada Komentar untuk "Rename the Attached as Thinker.txt and Read the Data Only, Using Scanf Command."
Posting Komentar