Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,851 questions

51,772 answers

573 users

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 234 views
1 answer 161 views
1 answer 535 views
1 answer 157 views
1 answer 201 views
1 answer 468 views
1 answer 206 views
...