#define _GNU_SOURCE
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
/**
* Prints an optional error message, and kills process.
* At the end of the error message, a newline is printed.
* If msg is a NULL pointer then nothing will be printed.
*/
void die(int status, const char *msg)
{
// print error message
if (msg) {
fprintf(stderr, "%s: %s\n", "mkcmain", msg);
}
exit(status);
}
int main(void)
{
const char *cmain_text = "int main(int argc, char *argv[])\n"
"{\n\n"
"\treturn 0;\n"
"}";
size_t cmain_text_size;
const char *filename = "main.c";
char *cw_dir;
char *filepath;
FILE *file;
// attempt getting current dir
errno = 0;
cw_dir = get_current_dir_name();
if(NULL == cw_dir) {
perror("get_current_dir_name()");
die(EXIT_FAILURE, "could not get current directory name");
}
// allocate memory for path
if (NULL == (filepath = malloc((strlen(cw_dir) + 1 + strlen(filename) + 1) * sizeof(char)))) {
die(EXIT_FAILURE, "could not allocate memory for file path name");
}
// construct file path
strcpy(filepath, cw_dir);
strcat(filepath, "/");
strcat(filepath, filename);
// try to open file for writing
errno = 0;
if (NULL == (file = fopen(filepath, "w"))) {
free(filepath);
perror("fopen");
fprintf(stderr, "%s: could not open %s for writing\n", "mkcmain", filepath);
die(EXIT_FAILURE, NULL);
}
// try to write C main file text to file
cmain_text_size = strlen(cmain_text);
if (fwrite(cmain_text, sizeof(char), cmain_text_size, file)
!= cmain_text_size * sizeof(char))
{
free(filepath);
fprintf(stderr, "%s: could not write to open file %s\n", "mkcmain", filepath);
die(EXIT_FAILURE, NULL);
}
// try to close the file
if (fclose(file)) {
free(filepath);
perror("fclose()");
die(EXIT_FAILURE, "encountered error during attempt to close file");
}
free(filepath);
exit(EXIT_SUCCESS);
}