Simple C Problem

Main Question or Discussion Point

Hey guys. I am trying to figure out how to use text input/output files in c. Here is the code that I have written, would someone please tell me what I am doing wrong?

#include<stdio.h>
#include<stdlib.h>
#pragma warning(disable:4996)

void main()
{
FILE *fp,*namefp, *gpafp;
char first[15], last[15], inbuf[80];
double gpa;
if((fp=fopen("c:\\Users\\Steve\\studinfo.txt","r")) == NULL)
{
printf("Unable to open input file\n");
exit(1);
}
if((namefp=fopen("c:\\Users\\Steve\\names.txt","w"))== NULL);
{
printf("unable to open names file\n");
exit(2);
}

if((namefp=fopen("c:\\Users\\Steve\\gpas.txt","w")) == NULL);
{
printf("unable to open gpa file\n");
exit(3);
}

while(fgets(inbuf, 80, fp) != NULL)
{
sscanf(inbuf,"%s %s %f%*c", first, last, &gpa);
fprintf(namefp,"%s, %s\n", last,first);
fprintf(gpafp,"%4.2f\n",gpa);
} // end of while

fclose(fp);
fclose(namefp);
fclose(gpafp);

} // end of main
 

Answers and Replies

Here is what is contained in the file studinfo:
Albert Einstein 2.3
Salvadore Dali 3.1
Neamiah Scudder 1.4


Here is what is contained in the file names:
Einstein, Albert
Dali, Salvadore
Scudder, Neamiah


And here is what is in the file gpa:
2.33
3.13
1.44
 
jtbell
Mentor
15,403
3,191
What do you expect the output to be, and what do you actually get?
 
The output should simply print out the data from those files. I am getting "Unable to open input file". So the first if statement is TRUE.
 
jim mcnamara
Mentor
3,655
1,890
You are on Windows -
go into windows explorer and find the real location and name of the "studinfo.txt" file you are trying to open. LOSE the semicolons after the open statements and maybe it will work. As you code is written it will always exit in one of those accidental anonymous blocks you create by leaving the semicolons.

ps: int main( ) returns an int - add a last line in main: return 0; Don't use void main().

And what does that pragma do? disable warnings? Don't do that.... If you compile an run a program with warnings and it works, you are asking for trouble later on - it's called programming by coincidence and it will always come back to haunt you. I'll bet it doesn't like void main to start with....
 
What do you mean the "real" location?
 
Can anyone help me?
Those semi-colons after the if statements shouldn't be there. i.e. if((namefp=fopen("c:\\Users\\Steve\\gpas.txt","w") ) == NULL);
 
156
0
Indeed, the ; should not be there... what happens if you remove them?

By the way, you are using namefp as a FILE pointer twice; you should be using gpafp when trying to open the file gpas.txt.
 
got it! Thanks.
 

Related Threads for: Simple C Problem

Replies
8
Views
2K
Replies
2
Views
2K
Top