Reputation: 365
Right now, what I have is this:
#include <stdio.h>
#include <conio.h>
#include <string.h>
int main()
{
char fname[100];
FILE* fp;
memset(fname, 0, 100);
/* ask user for the name of the file */
printf("enter file name: ");
gets(fname);
fp = fopen(fname, "w");
/* Checks if the file us unable to be opened, then it shows the
error message */
if (fp == NULL)
printf("\nError, Unable to open the file for reading\n");
else
printf("hello");
getch();
}
This functions just fine, but is there a way I can force it to save as a .txt or a .data or something? Right now it just saves as the name you put in with no extension. Other than asking the user to just input the name and extension, I can't think of a way to do that. I mean, it still works just fine for reading/writing purposes, I just think an extension would be nice.
Upvotes: 0
Views: 157
Reputation: 365
I figured it out. Credit goes to a friend of mine who showed this to me earlier today.
int main()
{
FILE *Fileptr;
char filename[50];
char file[50];
int c;
printf("What do you want to name your file?");
scanf("%s", filename);
sprintf(file, "%s.txt", filename);
Fileptr = fopen(file, "w");
fprintf(Fileptr, "Data goes here");
fclose(Fileptr);
return 0;
}
Much easier than what I had been doing.
Upvotes: 0
Reputation: 11237
The strcat
function can be used to append text to a destination buffer, assuming the destination is large enough to store the new text.
char *strcat(char *destination, const char *source);
The source
is the new text that you want to append (in your case the extension), and the destination
is where the new text will be added. If destination
is not big enough, then the behavior is undefined.
One could also use the snprintf
function to append text, which is safer, as it takes a size argument.
Upvotes: 0