Home arrow C and C+ arrow Reading From a File in C Language
Reading From a File in C Language PDF
Wednesday, 08 February 2012
You must create a file plain.txt, with some text in it. This C program will read a text file and will print it on screen.

readfile2.c
#include <stdlib.h>
#include <stdio.h>

char * read_file(char *filename)
{
FILE *fp;
char *buffer;
size_t result;
long file_size;

if((fp = fopen(filename, "rb")) == NULL) {
    printf("\nCannot open file.\n");
    exit(1);
    }

/* get file size */
fseek(fp, 0, SEEK_END);
file_size=ftell(fp);
rewind(fp);

/* allocate memory */
buffer = (char *) malloc (sizeof(char)*file_size);
if (buffer == NULL) {
    printf("\nMemory error.\n");
    exit(2);
    }

/* copy the entire file into the buffer */
result = fread(buffer, 1, file_size, fp);
if (result != file_size) {
    printf("\nReading error.\n");
    exit(3);
    }

fclose(fp);
return buffer;
}

int main(int argc, char *argv[])
{
char *buffer;
buffer=NULL;
buffer=read_file("plain.txt");

printf("Buffer: \n%s", buffer);

printf("\n");
return 0;
}


 
Next >

Other BSD Systems

OpenBSD

Misc

Solaris

Polls

Best BSD firewall?