In: Computer Science
C Programming
Write a program in C that reads in a file, stores its contents as a character array/pointer (char*) into an unsigned character array/pointer (unsigned char* message).
Note: the input file can have one line or multiple lines and vary in length
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
long lSize;
char *buffer;
fp = fopen ( "a.txt" , "rb" );
if( !fp ) perror("a.txt"),exit(1);
fseek( fp , 0L , SEEK_END);
lSize = ftell( fp );
rewind( fp );
buffer = calloc( 1, lSize+1 );
if( !buffer ) fclose(fp),fputs("memory alloc
fails",stderr),exit(1);
if( 1!=fread( buffer , lSize, 1 , fp) )
fclose(fp),free(buffer),fputs("entire read
fails",stderr),exit(1);
unsigned char* message =( unsigned char*) buffer;
for (long k= 0; k <lSize; k++)
{
printf("%c",message[k]);
}
fclose(fp);
free(buffer);
return 0;
}