Linux C程序练习(1)文件操作

本文提供两个C语言程序示例:一个用于复制文件,另一个用于读取指定目录下的所有文件名。通过这两个示例,读者可以了解如何使用C语言进行基本的文件操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/stat.h>

#define BUFFERSIZE 1024

typedef int fid_t;

int main(int argc,char **argv){
    fid_t fd1=0;
    fid_t fd2=0;
    int readBytes=0;
    char *buffer=NULL;

    buffer=(char*)malloc(BUFFERSIZE*sizeof(char));
    memset(buffer,0,BUFFERSIZE*sizeof(char));
    
    fd1=open("/etc/passwd",O_RDONLY);
    if(fd1<0){
    	perror("open(fd1)");
    	exit(1);
    }
    
    fd2=open("passwd.bak",O_CREAT|O_RDWR|O_EXCL,0644);
    if(fd2<0){
    	perror("open(fd2)");
    	exit(1);
    }

	while((readBytes=read(fd1,buffer,BUFFERSIZE))>0){
		if(write(fd2,buffer,BUFFERSIZE)<0){
			perror("write(fd2)");
			exit(1);
		}
		memset(buffer,0,BUFFERSIZE*sizeof(char));
	}
	
	if(readBytes<0){
		perror("read(fd1)");
		exit(1);
	}
	close(fd1);
	close(fd2);
	exit(0);
}

copy1.c 复制文件

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <dirent.h>
#include <errno.h>

DIR *opendir(const char *name);

int main(int argc,char **argv){
    int ret=0;
    int count=0;
    DIR *dp;
    struct dirent *dirent;

    if(argc!=2){
        printf("usage:readdir<staring-pathname>\n");
        exit(1);
    }
	
	dp=opendir(argv[1]);
	if(dp==NULL){
		perror("opendir()");
		exit(1);
	}
	
	while((dirent=readdir(dp))!=NULL){
		count++;
		printf("file[%2d]:->%s\n",count,dirent->d_name);
	}
    if(errno){
    	perror("readdir()");
    	exit(1);
    } 
	exit(0);
}
readdir1.c读目录下的文件
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值