icp/oer/courses/c-basics/sections/26-files/01-read/program.c

38 lines
1.1 KiB
C

#include <stdio.h>
#include <stdlib.h>
int main(int argc, const char *argv[])
{
// First we must open the file. we have to pass the name and our mode.
// we only want to read so we pass "r"
FILE *file = fopen("Lorem_Ipsum.txt","r");
// Check if we succeded
if(file)
{
// TODO: Read up on how to get the filesize and the data from the file with stdio
// tipp: fseek, ftell, fread ...
// TODO: Get the filesize
int Filesize = 0;
char *Buffer = malloc(sizeof(char)*(Filesize+1));
Buffer[Filesize] = 0;
// This is optianal but it is sometimes convenient to nullterminate your buffer
// If you dont want to do that you just have to allocate the exact amount
// TODO: Copy the data into the Buffer
// Now you have read the data into a buffer and you could mess with it, if you wanted to.
// For now were will just print it out;
printf("%s", Buffer);
// if you use the file the whole liftime of the program you actualy don't need to close it.
fclose(file);
}
else
{
// Here you could write your error handling or log the error;
}
}