文件读取的操作练习

这个技巧也可用于判断我们是否可以改变某个文件的偏移量。如果参数 fd(文件描述符)指定的是 pipe(管道)、FIFO 或者 socket,lseek 返回 -1 并且置 errno 为 ESPIPE。


C语言文件操作函数大全   

/*#include<stdio.h>
int main()
{
	FILE *file_handle = fopen("f1.txt","w");
	//while(!feof(file_handle))
	{
		fwrite("hello",sizeof("hello"),1,file_handle);
	}
	fclose(file_handle);
	file_handle = NULL;
	return 0;
}*/
#include<stdio.h>
int main()
{
	FILE *file_handle = fopen("f1.txt","r");
	char buffer[1000];
	while(!feof(file_handle))
	{
		fseek(file_handle,3,SEEK_SET);
		printf("%d   ",ftell(file_handle));
		fread(buffer,1000,1,file_handle);
		//fputs("hello\n");
		fprintf(stderr,"%s\n",buffer);
		//fwrite("hello",sizeof("hello"),1,file_handle);
	}
	//fseek(file_handle, 0, SEEK_SET);
	rewind(file_handle);
	fread(buffer,1000,1,file_handle);
	fprintf(stderr,"%s\n",buffer);

	fclose(file_handle);
	file_handle = NULL;
	return 0;
}
/*
#include<stdio.h>
main()
{
FILE * stream;
long offset;
fpos_t pos;
stream=fopen(“/etc/passwd”,”r”);
fseek(stream,5,SEEK_SET);
printf(“offset=%d/n”,ftell(stream));
rewind(stream);
fgetpos(stream,&pos);
printf(“offset=%d/n”,pos);
pos=10;
fsetpos(stream,&pos);
printf(“offset = %d/n”,ftell(stream));
fclose(stream);
}
*/
/*
#include <string.h>
#include <stdio.h>
int main(void)
{
	FILE *stream;
	char string[] = "This is a test";
	fpos_t filepos;
	stream = fopen("f1.txt", "w+");
	fwrite(string, strlen(string), 1, stream);
	fgetpos(stream, &filepos);
	printf("The file pointer is at byte %ld\n", filepos);
	fclose(stream);
	return 0;
}
*/

/*
#include <stdio.h>
struct mystruct
{
    int i;
    char cha;
};
 
int main(void)
{
    FILE *stream;
    struct mystruct s;
    if ((stream = fopen("TEST.txt", "wb")) == NULL) // open file TEST.$$$
    {
        fprintf(stderr, "Cannot open output file.\n");
        return 1;
    }
    s.i = 0;
    s.cha = 'A';
    fwrite(&s, sizeof(s), 1, stream); // 写的struct文件
    fclose(stream); //关闭文件
    return 0;
}*/




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值