c++ FILE*问题,好的追加悬赏!
如何以同时读写的方式打开文件?打开之后怎么同时读写?读写的时候文件位置指针怎么移动?麻烦给一个例子,谢谢!...
如何以同时读写的方式打开文件?打开之后怎么同时读写?读写的时候文件位置指针怎么移动?麻烦给一个例子,谢谢!
展开
1个回答
展开全部
"r+" Open a text file for read/write
"w+" Create a text file for read/write
"a+" Open a text file for read/write
"rb+" Open a binary file for read/write
"wb+" Create a binary file for read/write
"ab+" Open a binary file for read/write
移动文件位置指针:
int fseek( FILE *stream, long offset, int origin );
origin的虚如丛值有如下三种:
SEEK_SET Seek from the start of the file 文件开始
SEEK_CUR Seek from the current location 当前位置
SEEK_END Seek from the end of the file 文件结尾
返回文件当前位置:
long ftell( FILE *stream );
例子:
#include<stdio.h>
int main()
{
FILE *fp = fopen("1.txt","w+");//如果文件不存在会新建,否则会覆盖
if(NULL == fp)
{
puts("Can't open file!");
return 1;
}
int n = 123;
char s[1005] = "Hello World!\n";
fprintf(fp,"%s",s);
fprintf(fp,"%d\n",n);
fseek(fp,6,SEEK_SET);//跳到文件开始第6个位置,即'W'的位置
fscanf(fp,"%s",s);
puts(s);
printf("Current pos: %d\n",ftell(fp));//此时位置是'!'的位置
fseek(fp,-4,SEEK_END);//跳到结尾前的4个字符:2,3,两差樱个换行
printf("Current pos: %d\n",ftell(fp));//此时的位置是2的位置
fscanf(fp,"橡盯%d",&n);
printf("%d\n",n);
fclose(fp);
return 0;
}
输出:
World!
Current pos: 12
Current pos: 15
23
文件内容:
Hello World!
123
"w+" Create a text file for read/write
"a+" Open a text file for read/write
"rb+" Open a binary file for read/write
"wb+" Create a binary file for read/write
"ab+" Open a binary file for read/write
移动文件位置指针:
int fseek( FILE *stream, long offset, int origin );
origin的虚如丛值有如下三种:
SEEK_SET Seek from the start of the file 文件开始
SEEK_CUR Seek from the current location 当前位置
SEEK_END Seek from the end of the file 文件结尾
返回文件当前位置:
long ftell( FILE *stream );
例子:
#include<stdio.h>
int main()
{
FILE *fp = fopen("1.txt","w+");//如果文件不存在会新建,否则会覆盖
if(NULL == fp)
{
puts("Can't open file!");
return 1;
}
int n = 123;
char s[1005] = "Hello World!\n";
fprintf(fp,"%s",s);
fprintf(fp,"%d\n",n);
fseek(fp,6,SEEK_SET);//跳到文件开始第6个位置,即'W'的位置
fscanf(fp,"%s",s);
puts(s);
printf("Current pos: %d\n",ftell(fp));//此时位置是'!'的位置
fseek(fp,-4,SEEK_END);//跳到结尾前的4个字符:2,3,两差樱个换行
printf("Current pos: %d\n",ftell(fp));//此时的位置是2的位置
fscanf(fp,"橡盯%d",&n);
printf("%d\n",n);
fclose(fp);
return 0;
}
输出:
World!
Current pos: 12
Current pos: 15
23
文件内容:
Hello World!
123
更多追问追答
追问
请问wb+和rb+有什么区别?
追答
wb+如果文件不存在会新建,否则会覆盖
rb+如果文件不存在出错,否则读取
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询