g*********s 发帖数: 1782 | 1 如果单线程程序,两个对象共享一个FILE*指针会有问题吗?
比如每个对象都有个_fp私有成员,某个对象打开文件时做:
FILE* fp = fopen("foo.txt", r);
obj1->set_fp(fp);
obj2->set_fp(fp);
obj1->read_info(offset1);
// move file pointer to offset1 and read from file foo.txt.
obj2->read_info(offset2);
...
fclose(fp);
obj1->set_fp(NULL);
obj2->set_fp(NULL); |
P********e 发帖数: 2610 | 2 "r"是没问题的
【在 g*********s 的大作中提到】 : 如果单线程程序,两个对象共享一个FILE*指针会有问题吗? : 比如每个对象都有个_fp私有成员,某个对象打开文件时做: : FILE* fp = fopen("foo.txt", r); : obj1->set_fp(fp); : obj2->set_fp(fp); : obj1->read_info(offset1); : // move file pointer to offset1 and read from file foo.txt. : obj2->read_info(offset2); : ... : fclose(fp);
|
m*****e 发帖数: 4193 | 3
Yes.
【在 g*********s 的大作中提到】 : 如果单线程程序,两个对象共享一个FILE*指针会有问题吗? : 比如每个对象都有个_fp私有成员,某个对象打开文件时做: : FILE* fp = fopen("foo.txt", r); : obj1->set_fp(fp); : obj2->set_fp(fp); : obj1->read_info(offset1); : // move file pointer to offset1 and read from file foo.txt. : obj2->read_info(offset2); : ... : fclose(fp);
|
t****t 发帖数: 6806 | 4 you can do that. however beware, it's dangerous to mix FILE operations. for
example, you must do a seek between read and write; if you do read in one
and write in another one, you could miss the seek.
【在 g*********s 的大作中提到】 : 如果单线程程序,两个对象共享一个FILE*指针会有问题吗? : 比如每个对象都有个_fp私有成员,某个对象打开文件时做: : FILE* fp = fopen("foo.txt", r); : obj1->set_fp(fp); : obj2->set_fp(fp); : obj1->read_info(offset1); : // move file pointer to offset1 and read from file foo.txt. : obj2->read_info(offset2); : ... : fclose(fp);
|
r*********r 发帖数: 3195 | 5 c++ 里用 FILE * 太底层了.
中间随便哪个地方出个 exception, fclose 就到不了. |