Reputation: 25
I have the following program:
#include <stdio.h>
#include <conio.h>
main(char name[31], int phone)
{
FILE *file;
file=fopen("data.txt","w");
if (file==NULL)
{
file=fopen("data.txt","w");
printf("Name : ");
scanf("%s",&name);
printf("\nPhone number : ");
scanf("%d",&phone);
printf("Your booking number is : ");
fprintf(file,"%s;%d\n",name,phone);
fclose(file);
}
else
{
file=fopen("data.txt","a");
printf("Name : ");
scanf("%s",&name);
printf("\nPhone number : ");
scanf("%d",&phone);
fprintf(file,"%s;%d\n",name,phone);
fclose(file);
}
}
When I compile and run the program, the program asks for a name. After I input a name, an alert comes up and closes the program. The program used to work, but after restarting the computer it now has this new behaviour.
What might be wrong?
Upvotes: 0
Views: 79
Reputation: 8866
This program has some fairly serious problems.
Smallest first - fix your formatting, please. You're making it harder for yourself to notice bugs. If you can't read your code, you can't debug it.
Next is your main
function declaration:
main(char name[31], int phone)
This is not how you define main
. Its definition must be this:
int main()
{
//code here
}
I'm somewhat surprised that definition even compiles.
What you'll probably want to do instead is just declare name
and phone
as normal variables within main
, just like you declared file
.
EDIT: as pointed out by @Namfuak in the comments, main
can take an alternate form:
int main(int argc, char** argv)
{
//code here
}
In this form, argc
holds the number of parameters passed on the command-line to your program, and argv
holds the parameters themselves. However, you don't need this form, since you're getting user input from stdin. Just the parameter-less int main()
version will suffice for your needs.
Moving on to your file access...
file=fopen("data.txt","w");
if (file==NULL)
{
file=fopen("data.txt","w");
You're trying to open the file, and if it won't open you open it again? Don't do that, please. It's not a good idea; if the file won't open once, trying again won't do anything special for you.
Similarly,
else
{
file=fopen("data.txt","a");
This really isn't a good idea either. If file
isn't null, it means you managed to open the file successfully. Why are you trying to reopen it without closing it...?
What it looks to me like you're trying to do is test to see if the file exists, and append to it if it does, or create & open it if it doesn't. You just need to use the "a" flag, though, per the fopen docs (emphasis mine):
append: Open file for output at the end of a file. Output operations always write data at the end of the file, expanding it. Repositioning operations (fseek, fsetpos, rewind) are ignored. The file is created if it does not exist.
So if you just open the file in append ("a"
) mode and make sure file
isn't null, you can safely write to it. Either it won't exist so you'll create it, or it'll exist and you'll open it.
Upvotes: 4