Read the contents of a file into character buffer using C program

Lets say we want to read the contents of some file and want to operate on these contents using C program. In this case, we first need to read the complete file into buffer and work on to this character buffer to do what we want to do.

Following c program, copied the contents of JSON file test_file.json into buffer [ You can do whatever you want which this bufffer ]

 $ vim read_file_to_buffer.c 
[bash] #include <stdio.h> #include <stdlib.h> #include <stdbool.h> char *read_file(const char *filename) { ssize_t size; int fd, len; struct stat st; char *buf; stat(filename, &st); len = st.st_size; buf = (char *)malloc(len+1); fd = open(filename, O_RDONLY); if (fd == -1) { free(buf); return NULL; } size = read(fd, buf, len); if (size > 0) { buf[len]=’\0’; close(fd); printf("read bytes : %d, len:%d\n", strlen(buf), len); return buf; } close(fd); return NULL; } int main(void) { char *buf = NULL; buf = read_file("./test_file.json"); free( buf ); return 0; } [/bash]
 $ gcc -o read_file_to_buffer read_file_to_buffer.c 
 $ ./read_file_to_buffer 

This program assumes, the file we need to read test_file.json is present in the current directory from where this program is executed, if not you can customise the program as you want.

Leave a Comment