C/C++流和文件
我有以下代码:
int checkCorrectness(int i,char *iStr)
{
if(atoi(iStr) == i)
return 1;
return 0;
}
void foo(int i)
{
printf("inside foo %d\n",i);
}
void print()
{
char mystring[100];
freopen("myfile.txt","w+",stdout);
for(int i =0;i < 100;++i)
{
foo(i);
FILE *f = fopen("myfile.txt","r");
if (f == NULL) perror ("Error opening file");
else {
while ( fgets (mystring , 100 , f) != NULL );
if(!checkCorrectness(i,mystring);
break;
fclose (f);
}
}
fclose(stdout);
}
这段代码是否保存?我的意思是在调用 freopen 并且其流未关闭后调用 fopen 可以吗?谢谢
I have the following code:
int checkCorrectness(int i,char *iStr)
{
if(atoi(iStr) == i)
return 1;
return 0;
}
void foo(int i)
{
printf("inside foo %d\n",i);
}
void print()
{
char mystring[100];
freopen("myfile.txt","w+",stdout);
for(int i =0;i < 100;++i)
{
foo(i);
FILE *f = fopen("myfile.txt","r");
if (f == NULL) perror ("Error opening file");
else {
while ( fgets (mystring , 100 , f) != NULL );
if(!checkCorrectness(i,mystring);
break;
fclose (f);
}
}
fclose(stdout);
}
Is this code save?I mean is it OK to call fopen after freopen was called and its stream was not closed? Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你的代码看起来很安全。您可以在一个进程中多次打开同一个文件。文件描述符不会相互干扰。
我会避免像你一样重新打开标准输出。您可以使用单个 fopen 来完成整个程序,并避免您造成的混乱:查找 fprintf!
Your code looks safe. You are allowed to open the same file more than once in a process. The file descriptors will not interract.
I'd steer away from reopening stdout like you do. You could do this entire program with a single fopen and avoid the mess you're creating: look up fprintf!