File Handling in C (Reading a file line by line)

In this tutorial, we are working with the files in the C.

file logo



File handling in any language requires Three main steps to follow

  1. Open the file in Read/Write mode.
  2. Do various operation that you want to do.
  3. Close the file.

We are using fopen(file stream).

there is some modes to open a file.

  1. Read mode opens file into the read mode if file not found returns -1.
  2. Write mode opens file into the write mode if the file does not present creates a new file if there is previous data it will be overwritten.
  3. Append mode opens the file in the append mode and append data to it


Without wasting much time lets start working.

Create a New C file of whatever name you want mine is files.c.

create the basic schema of C language.

#include <stdio.h>

int main(int argc, char const *argv[])
{
/* code */
return 0;
}

Read From the file


Create a FILE pointer to point a stream and open a file into the read mode using "r".
you may need to include the string.h to your headers.

the data of the file is
data.txt file pic


#include <stdio.h>

int main(){
FILE *fp;
// suppose the size of the line is 128 character.
char line[128];
fp = fopen("data.txt", "r");

while (fgets(line, sizeof(line), fp)) {
printf("%s\n",line );
}
fclose(fp);
return 0;
}

output of this code is

output of this code

 this is reading from the file.

Write to a File

so for the writing, we have to open the same file into the write mode.

example program for this is.

#include <stdio.h>

int main(){
FILE *fp;
// suppose the size of the line is 128 character.
char line[128];
fp = fopen("data.txt", "w");

for (int iter = 0; iter < 20; ++iter)
{
fprintf(fp, "%d\n",iter );
}
printf("Data written to file\n");
fclose(fp);
return 0;
}

the output of this program is.

data.txt alt textwrite file output

we can also try for the append mode but to keep the tutorial short let's wrap it up here. append works in the same way.

in this mode, previous data is not deleted and new data appended to the file.

Thanks for being here.
if you loved this post please check my other post for the file handling in c++

you can also check out my other post for the various programming language.

Comments

Popular posts from this blog

Third Equation of motion, How to implement using C language

Second Equation of motion, How to implement using C language

First Equation of motion, How to implement using C language