在 C 中一起使用 fscanf 和 fprintf
Using fscanf and fprintf together in C
#include <stdio.h>
#include <stdlib.h>
#define FILE_NAME "ff.txt"
int main() {
char x[10],y[10];
FILE *fp;
fp = fopen(FILE_NAME, "r+");
if (fp == NULL) {
printf("couldn't find %s\n ",FILE_NAME);
exit(EXIT_FAILURE);
}
fprintf(fp,"Hello2 World\n");
fflush(fp);
fscanf(fp,"%s %s",x,y);
printf("%s %s",x,y);
fclose(fp);
return 0;
}
这是我正在尝试做的事情的简化版本。此代码不会在控制台中打印任何内容。如果我删除 fprintf
调用,它会打印文件中的前 2 个字符串,对我来说是 Hello2 World
。为什么会这样?即使在我 fflush
fp
?
在 fprintf()
, the file pointer points to the end of the file. You can use fseek()
之后将文件指针设置在文件的开头:
fprintf(fp,"Hello2 World\n");
fflush(fp);
fseek(fp, 0, SEEK_SET);
fscanf(fp,"%s %s",x,y);
或者按照@Peter 的建议更好,使用rewind()
:
rewind(fp);
rewind
:
The end-of-file and error internal indicators associated to the stream
are cleared after a successful call to this function, and all effects
from previous calls to ungetc on this stream are dropped.
On streams open for update (read+write), a call to rewind allows to
switch between reading and writing.
最好也检查 fscanf()
的 return 代码。
为避免缓冲区溢出,您可以使用:
fscanf(fp,"%9s %9s",x,y);
#include <stdio.h>
#include <stdlib.h>
#define FILE_NAME "ff.txt"
int main() {
char x[10],y[10];
FILE *fp;
fp = fopen(FILE_NAME, "r+");
if (fp == NULL) {
printf("couldn't find %s\n ",FILE_NAME);
exit(EXIT_FAILURE);
}
fprintf(fp,"Hello2 World\n");
fflush(fp);
fscanf(fp,"%s %s",x,y);
printf("%s %s",x,y);
fclose(fp);
return 0;
}
这是我正在尝试做的事情的简化版本。此代码不会在控制台中打印任何内容。如果我删除 fprintf
调用,它会打印文件中的前 2 个字符串,对我来说是 Hello2 World
。为什么会这样?即使在我 fflush
fp
?
在 fprintf()
, the file pointer points to the end of the file. You can use fseek()
之后将文件指针设置在文件的开头:
fprintf(fp,"Hello2 World\n");
fflush(fp);
fseek(fp, 0, SEEK_SET);
fscanf(fp,"%s %s",x,y);
或者按照@Peter 的建议更好,使用rewind()
:
rewind(fp);
rewind
:The end-of-file and error internal indicators associated to the stream are cleared after a successful call to this function, and all effects from previous calls to ungetc on this stream are dropped.
On streams open for update (read+write), a call to rewind allows to switch between reading and writing.
最好也检查 fscanf()
的 return 代码。
为避免缓冲区溢出,您可以使用:
fscanf(fp,"%9s %9s",x,y);