Read file in C

Dear student today we learn about the Program that read your .txt file from your File. Here we have two ways to read the .txt file using C Program through Recursion Function. Read file in C Program


//Read file in C Program

#include <stdio.h>

int read_file_recurse(FILE *fp)

{

char buf[512];

if (fgets(buf, 512, fp) == NULL) return 0;

printf(“%s”,buf);

return read_file_recurse(fp);

}

int main()

{

FILE *f=fopen(“myfile.txt”,”r”);

read_file_recurse(f);

return 0;

}

Note:- I hope this program will help you in understanding Recursion Function How to Read file in C Program

How to Read file in C Program

//Read file in C Program
#include <stdio.h>

#include<string.h>

void readFile(FILE* f){

char bufc[512];

if (fgets(bufc, 512, f) == NULL){fclose(f); f=NULL; return;}

printf("%s",bufc);

readFile(f);

}

void read_file_recurse(FILE *fp)

{

char buf[512];

if(fgets(buf, 512, fp) == NULL){fclose(fp); fp=NULL; return;}

else{

buf[strlen(buf) - 1] = '\0'; // omit the \n character in the file path read from file

printf("File= %s\n",buf);

FILE *tf =fopen(buf,"r");

if (tf == NULL) {

perror("Failed: ");

return ;

}

else{

readFile(tf);

printf("\n\n");

}

printf("\n");

read_file_recurse(fp);
}
int main()
{
FILE *f=fopen("myfile.txt","r"); // remember to enter new line at the end of last line in the file

read_file_recurse(f);

fclose(f);

return 0;

}

Read file in C line by line

You need to create a Text File which extension is “.txt”, in the same directory where you saved your Program. then this program will be returned to you, which is inside your “.text” file. Read file in C Program

Read text file in C

Read file in C
Read file in C

END

C read text File

Leave a Reply

x