i am trying to figure out how to check if a file exists in my void existing_file(void) function, and if not i would like to create it. The big thing that i am trying to do is prompt the user for a file path and also prompt the user for a name and append the name to the end of the path. Then use this path to make a new file! Also, how do i write a function that actually opens the file and shows it on the screen?
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void new_file();
void existing_file();
struct date {
int day;
int month;
int year;
} birth;
int main(void)
{
int option;
printf("1. Create a new file\n");
printf("2. Open an existing file\n");
printf("3. Exit program\n");
printf("Enter option number: ");
scanf("%d", &option);
switch(option) {
case 1:
new_file();
break;
case 2:
existing_file();
break;
case 3:
exit(1);
break;
}
}
void new_file(void)
{
FILE *fp_a;
FILE *fp_o;
fp_o = fopen("/home/anthony/Documents/new.txt", "w");
printf("Please enter your day of birth: ");
scanf("%d", &birth.day);
printf("Please enter your month of birth: ");
scanf("%d", &birth.month);
printf("Please enter your year of birth: ");
scanf("%d", &birth.year);
fp_a = fopen("/home/anthony/Documents/new.txt", "a+");
fprintf(fp_a, "%d %d %d", birth.day, birth.month, birth.year);
fclose(fp_a);
fclose(fp_o);
}
void existing_file(void)
{
FILE *fp_e;
char path[50];
printf("Enter the file path: ");
scanf("%c", &path);
if(fp_e = (fopen("path", "a")==NULL)) printf("Cannot open file for appending!");
else printf("File has been opened for appending.");
if(fp_e)
fclose(fp_e);
}
Thanks in advanced!!