work1.c

来自「Linux下的C代码 实现了对Linux的文件系统的操作」· C语言 代码 · 共 69 行

C
69
字号
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define MAXSIZE 101
main()
{
	//使用标准函数
    printf("Now is stantard:\n");
	int i,j,fd,size,len,buf[101];
	for(i=1;i<=100;i++) buf[i-1]=i;  //生成buff缓冲
	int buf_r[MAXSIZE];
    //open创建文件
    if((fd=open("tmp.c",O_CREAT | O_TRUNC | O_RDWR,0666))<0) {  
       perror("");
       exit(1);
    }
        
    //write向文件中写入内容
    if((fd=write(buf,fd,101)<0) {  
        perror("");
        exit(1);
    }
  	lseek(fd,49,0);  //更改当前指针位置,自原点偏移49,即第50个字节处
  	for(j=0;j<MAXSIZE;j++) buf_r[j]=0;
   	read(fd,buf_r,1);  
	printf("\nThe 50th byte is:%d \n",buf_r);  //读取该字节处内容并打印
	lseek(fd,99,0); //更改当前指针位置,自原点偏移99,即第100个字节处
	for(j=0;j<MAXSIZE;j++) buf_r[j]=0;
	read(fd,buf_r,1);
    printf("\nThe 100th byte is:%d \n",buf_r);  //读取该字节处内容并打印
    //close关闭文件
    if(close(fd)<0){
         perror("");
         exit(1);
    }

	//使用IO库
	FILE *fp;  //生成FILE指针
	char ch;
	if((fp=fopen("myfile.txt","w"))==NULL)  //fopen创建文件
	{
	printf("File cannot be opened\n");
	exit(1);
	}
	
	for(i=0;i<=100;i++)  //向文件内写入内容
	{
	if(i!=100)
		fputc(i,fp);	
	else
		{	
			fputc(i,fp);
			fputs("\0",fp);
		}
	}
	printf("Now is IO:\n");
	fseek(fp,49,SEEK_SET); //更改当前指针位置,自原点偏移49,即第50个字节处
	//while((ch=fgetc(fp))!=EOF)
	printf("The 50th byte is:%c\n",fgetc(fp));
	fseek(fp,99,SEEK_SET); //更改当前指针位置,自原点偏移99,即第100个字节处
	//while((ch=fgetc(fp))!=EOF)
	printf("The 100th byte is:%c\n",fgetc(fp));
	fclose(fp);  //fclose关闭文件
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?