#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
int writeToFile(char* filename, char* first, ...) {
FILE* fp = fopen(filename, "wb");
if (!fp) { fputs("File open error", stderr); return 0; }
va_list vl;
va_start(vl, first);
char* s = first;
while (s != 0) {
vfprintf(fp, s, vl);
s = va_arg(vl, char*);
}
fclose(fp);
va_end(vl);
return 1;
}
int readFile(char* filename) {
FILE* fp = fopen(filename, "rb");
if (!fp) { fputs("File open error", stderr); return 0; }
fseek(fp, 0, SEEK_END);
long file_size = ftell(fp);
rewind(fp); // sets fp to the beginning of the file
char* buffer = (char *)malloc(sizeof(char) * file_size + 1);
if (!buffer) { fputs("Memory allocation error", stderr); return 0; }
size_t rv = fread(buffer, 1, file_size, fp); // copy the file content into a buffer
if (rv != file_size) { fputs("File reading error", stderr); return 0; }
buffer[file_size] = '\0';
printf("file content = %s", buffer);
fclose(fp);
free(buffer);
return 1;
}
int main()
{
char* filename = "d:\\data.bin";
writeToFile(filename, "c", "c++", "java", "python");
readFile(filename);
return 0;
}
/*
run:
file content = cc++javapython
*/