Im struggleing by trying to read the files content into a string (char*). I just have to use the stdio.h libary, so I cant allocate memory with malloc.
How can I read all the content of a file and return it into a string?
Im struggleing by trying to read the files content into a string (char*). I just have to use the stdio.h libary, so I cant allocate memory with malloc.
How can I read all the content of a file and return it into a string?
I will attempt to answer your question. Keep in mind though - I am still fairly new to C, so there could be a better solution out there in which case please let me know about it too! :)
EDIT: And there was...
Here is how I see it... You need to know the size of the file you want to store in a string. More precisely - in the example solution that I'm providing, you need to know how many chars are in your input file.
All you are doing with malloc
is dynamically allocating memory on the 'heap'. I presume you already know that...
So regardless of where your string
lives in memory (stack or heap) you need to know how big that string
has to be, so all of the contents of your input file would fit in to it.
Here is a quick pseudo-code and some code with a solution to your problem... I hope this is helpful and I am open to learn a better approach if there is one, peace!
Pseudo-code:
open input file for reading
find out the size of the file
forward seek file position indicator to the end of the file
get the total number of bytes (chars) in infile
rewind file position indicator back to the start (because we will be reading from it again)
declare a char array, size of - all counted chars in infile + 1 for '\0' at the end of the string.
read all chars of infile in to the array
Terminate your string with '\0'
Close input file
Here is a simple program that does just that and prints your string:
#include <stdio.h>
int main(void)
{
// Open input file
FILE *infile = fopen("hello.py", "r");
if (!infile)
{
printf("Failed to open input file\n");
return 1;
}
////////////////////////////////
// Getting file size
// seek file position indicator to the end of the file
fseek(infile, 0L, SEEK_END);
// get the total number of bytes (chars) in infile
int size = ftell(infile); // ask for the position
// Rewind file position indicator back to the start of the file
rewind(infile);
//////////////////////////////////
// Declaring a char array, size of - all the chars from input file + 1 for the '\0'
char str[size + 1];
// Read all chars of infile in to the array
fread(&str, sizeof(char), size, infile);
// Terminate the string
str[size] = '\0'; // since we are zero indexed 'size' happens to be the last element of our array[size + 1]
printf("%s\n", str);
// Close the input file
fclose(infile);
// The end
return 0;
}