How to read all the content of text file at once in C

2 Answers

0 votes
#include <stdio.h>

int main()
{
    char file[100] = "d:\\data.txt";
	char buf[100] = "";
	
	FILE *fp = fopen(file, "r");
	
	fseek(fp, 0L, SEEK_END);
    int fsz = ftell(fp);
	fseek(fp, 0L, SEEK_SET);

    fread(buf, sizeof(char), fsz, fp);
	
	fclose(fp);

	printf("%s\n", buf);
	
    return 0;
}
 
   
   
   
/*
run:
   
c c++ c#
java python

*/

 

 



answered Jul 8, 2020 by avibootz
0 votes
#include <stdio.h>
#include <stdlib.h>

int main()
{
    char file[100] = "d:\\data.txt";
	char *buf;
	
	FILE *fp = fopen(file, "r");
	
	fseek(fp, 0L, SEEK_END);
    int fsz = ftell(fp);
	fseek(fp, 0L, SEEK_SET);
	
	buf = (char *) malloc(sizeof(char) * (fsz + 1));
	
	if (buf == NULL) {
		puts("malloc error");
		fclose(fp);
		exit(EXIT_FAILURE);
	}
	
    fread(buf, sizeof(char), fsz, fp);
	
	fclose(fp);

	buf[fsz - 1] = '\0';
	printf("%s\n", buf);
	
	free(buf);
	
    return 0;
}
 
   
   
   
/*
run:
   
c c++ c#
java python

*/

 



answered Jul 8, 2020 by avibootz

Related questions

2 answers 263 views
1 answer 168 views
1 answer 553 views
1 answer 174 views
1 answer 214 views
1 answer 487 views
1 answer 221 views
...