# fopen question

This is a discussion on fopen question within the C Programming forums, part of the General Programming Boards category; I want to open a file in C:\text.txt and print it. But, it doesn't work. What's wrong in the below ...

1. ## fopen question

I want to open a file in C:\text.txt and print it.

But, it doesn't work. What's wrong in the below statement?
thx!

#include <stdio.h>
void main()
{
int a,b;

b=fopen("c:\test.txt");
fscanf(b,"%d\n",&a);
printf("%d",a);

getchar();

}

2. You have the syntax of fopen all wrong. fopen returns a FILE * to the file you opened. The first parameter of fopen is the file, and second parameter (2 parameters in all) is the order of what you want to do ("r" -- read, "w" -- write). The syntax is:

<FILE * type> = fopen(filename, "r" or "w");

If you are working with binary files, you just add "b" with the "r" or "w". Your code, revised, would be:
Code:
#include <stdio.h>
void main()
{
int a;
FILE *fp;

fp=fopen("c:\test.txt", "r");
fscanf(fp,"%d",&a);
printf("%d",a);

getchar();

}
Understand???

--Garfield

i am using Visual Studio 6 and win 98 to run the program .

but it says Expression: str != NULL

can't find FSCANF.C.
However, I can't find FSCANF.C in my computer.

4. Post all of your code.

5. fscanf is a function in the stdio.h header library.

7. also... watch out for the backslash... the compiler will think that's an escape sequence, so you need to use a double backslash to get it...

8. Originally posted by Garfield
Just the code which u told me.

Code:
#include <stdio.h>
void main()
{
int a;
FILE *fp;

fp=fopen("c:\test.txt", "r");
fscanf(fp,"%d",&a);
printf("%d",a);

getchar();

}

9. As DA said, you have to use \\
Code:
fp=fopen("c:\\test.txt", "r");

10. I should use this method??

#include <stdio.h>
void main()
{
char a[200];
FILE *fp;

fp=fopen("c:\\test.txt", "r");
fscanf(fp,"%s",&a);
printf("%s",a);

getchar();

}

but, how can I read all the texts in a txt file since there is a limit for array?

11. And I just can read line 1 only.

12. Fixed code:

#include <stdio.h>
void main()
{
char a[100];
FILE *fp;

fp=fopen("c:\\test.txt", "r");

while (fscanf(fp,"%c",&a) != EOF)
{
printf("%c",a);
}
getchar();
fclose(fp);
}

13. Originally posted by GaPe
Fixed code:

#include <stdio.h>
void main()
{
char a[100];
FILE *fp;

fp=fopen("c:\\test.txt", "r");

while (fscanf(fp,"%c",&a) != EOF)
{
printf("%c",a);
}
getchar();
fclose(fp);
}
thx, but it appears some strange characters.

14. I did something like this:

Code:
#include <stdio.h>

void main()
{
char a[500];
FILE *fp;

fp=fopen("c:\\test.txt", "r");

while (fscanf(fp,"%s",&a) != EOF)
{
printf("%s",a);
}
getchar();
fclose(fp);
}
It can read the texts from a .txt file.
However, it prints all the texts in 1 line.

Page 1 of 2 12 Last