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