#include
#include
//fseek rewind fgetpos fsetpos
void movep();
/*
读文件
*/
void readfile();
/*
从控制台读取
*/
void readconsole();
/*
从字符串读取、写入字符串
将|符号换成&
*/
void readstring();
int main()
{
movep();
//readfile();
//readconsole();
//readstring();
return 0;
}
void readfile()
{
FILE *fp,*fp1;
int ch;
char buf[50];
//文件重命名
rename("aaddb.c","newname.c");
//删除文件
remove("client.o");
//创建临时文件,程序退出时自动销毁
fp = tmpfile();
putc('n',fp);//向其中写入一个字符
//读取文件getc
fp1 = fopen("client.c","r");
while((ch=getc(fp1)) != -1)
{
putc(ch,stdout);
}
fclose(fp1);
//读取文件fgets
fp1 = fopen("client.c","r");
while(fgets(buf,50,fp1) != NULL)
{
fputs(buf,stdout);
}
fclose(fp1);
//读写文件fread
fp1 = fopen("client.c","r");
fread(buf,sizeof(char),50,fp1);
fwrite(buf,sizeof(char),50,stdout);
fclose(fp1);
}
void readconsole()
{
char str[12],ch,str2[12];
//最基本的格式化读取
printf("input 'hello world'\n");
scanf("%[^\n]",str);//可以读取空格
printf("%s\n",str);
//读取字符
printf("input 'h'\n");
ch = getchar();//会读取回车键
putchar(ch);//所以会换行不会产生其他输出
putchar('\n');
//读取字符串
printf("input 'hello world'\n");
gets(str2);
puts(str2);
puts("\n");
}
void readstring()
{
char *str1,str2[22],arg1[4],arg2[3],arg3[11];
str1 = "you | me | him or her";
sscanf(str1,"%s | %s | %[^\n]",arg1,arg2,arg3);//从字符串中格式化读取,%[^\n]允许读入空格
printf("%s %s %s\n",arg1,arg2,arg3);//中间结果
sprintf(str2,"%s & %s & %s\n",arg1,arg2,arg3);//箱向字符串中格式化输出
printf("%s\n",str2);//最终结果
}
/*
ftell获得当前文件指针位置
fseek设置指针偏移,SEEK_SET以开头为基准,SEEK_CUR以当前位置为准,SEEK_END以结尾为准
fsetpos与fgetpos为一对控制偏移函数
rewind将指针返回开头
*/
void movep()
{
FILE * stream;
fpos_t pos;
stream = fopen("client.c","r");
fseek (stream,5,SEEK_SET);
printf("offset=%d\n", ftell (stream));
rewind (stream);//将指针指向文件开头
/* 取得指针位置并存入&pos所指向的对象 */
fgetpos (stream,&pos);
printf("offset=%d\n",pos);
pos = 10;
fsetpos (stream,&pos);
printf("offset = %d\n", ftell(stream));
fclose(stream);
}
stdio.h
最新推荐文章于 2024-07-21 17:01:16 发布