#include <stdio.h>
main() {
int n;
FILE *file;
printf("We are here to create a file!\n");
file = fopen("demo.txt", "w+");
if (file != NULL)
printf("Succesfully opened!");
printf("Enter number\n");
while (scanf("%d", &n)) {
fprintf(file, "%d", n);
}
fclose(file);
}
why fscanf()
is not working here? Here scanf
is working properly but fscanf()
is not responding or working here. Can anyone explain what the problem is?
Your code has some problems:
main
without arguments is int main(void)
fopen
returns NULL
because you later pass this null pointer to fprintf
. scanf()
returns 0
. You should instead iterate while scanf()
returns 1
. scanf()
will return EOF
if it fails at end of file, causing an infinite loop. fprintf()
otherwise all numbers are going to be clumped together forming a long sequence of digits. main()
should return 0
or an error status Here is a corrected version:
#include <stdio.h>
int main(void) {
int n;
FILE *file;
printf("We are here to create a file\n");
file = fopen("demo.txt", "w");
if (file != NULL) {
printf("Successfully opened\n");
} else {
printf("Cannot open demo.txt\n");
return 1;
}
printf("Enter numbers\n");
while (scanf("%d", &n) == 1) {
fprintf(file, "%d\n", n);
}
fclose(file);
return 0;
}
Regarding your question: why can't I use fscanf()
instead of scanf()
?
fscanf()
as long as you give it a stream pointer opened for reading: if you write while (fscanf(stdin, "%d", &n) == 1)
the program will behave the same way. fscanf()
to read from file
, you need to perform a file positioning command between read and write operations, such as rewind()
of fseek()
. Yet fscanf()
will fail if there is no number to read at the current position in the file and since you open file
with "w+"
mode, fopen()
will be truncated it. You could cause an infinite loop by writing a number to the file, rewinding it to the beginning and re-reading the same number, etc.
Here is some code for illustration:
#include <stdio.h>
int main(void) {
int n;
FILE *file;
printf("We are here to create a file\n");
file = fopen("demo.txt", "w+");
if (file != NULL) {
printf("Successfully opened\n");
} else {
printf("Cannot open demo.txt\n");
return 1;
}
printf("Enter a number: ");
if (scanf("%d", &n) == 1) {
fprintf(file, "%d\n", n);
rewind(file);
while (fscanf(file, "%d", &n) == 1) {
printf("read %d from the file\n", n);
if (n == 0)
break;
rewind(file);
fprintf(file, "%d\n", n >> 1);
rewind(file);
}
}
fclose(file);
return 0;
}
Interaction:
We are here to create a file
Successfully opened
Enter a number: 10
read 10 from the file
read 5 from the file
read 2 from the file
read 1 from the file
read 0 from the file
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.