吐槽
都已经大二了,老师既然还教我们C语言的基础open函数的使用,感到无力!!!只能粤嵌牛逼
要求
作业1:尝试从文件中读取某些字节? test.txt
作业2: test.txt,如果该文件存在则清空,不存在则创建,写入"hello"
作业3: 完成copy.c的拷贝 例如: ./copy 1.txt 2.txt
//
// Created by 90822 on 2020/5/7.
//
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#define BUFFER_MAX 1024
int fd1 = 0, fd2 = 0;
int wt1 = 0;
int size1 = 0, size2 = 0;
char buffer1[] = {} ,buffer2[] = {} ;
int work1(char *path);
int work2(char *path);
int work3(char *path1, char *path2);
int main(int argc, char* argv[]){
char *path1 = "../test1.txt";
char *path2 = "../test2.txt";
work1(path1); //作业1
work2(path2); //作业2
work3(path1, path2);//作业3
return 0;
}
int work1(char *path) {
printf("\n作业要求一\n");
if ((fd1 = open(path, O_RDONLY)) < 0) {
printf("你的test1.txt文件出现错误!");
exit(-1);
} else {
printf("文件描述符为:%d\n", fd1);
}
if ((size1 = read(fd1, buffer1, BUFFER_MAX)) < 0) {
printf("文件读取失败,请检查文件!\n");
exit(-1);
} else {
printf("文件内容为:%s\n", buffer1);
close(fd1);
}
printf("******************************************************************\n");
}
int work2(char *path){
printf("\n作业要求二\n");
char buf[] = "靓仔";
if((fd2 = open(path, O_WRONLY | O_CREAT | O_TRUNC)) < 0 && (size2 = read(fd2, buffer2, BUFFER_MAX)) < 0){
printf("你的test1.txt文件出现错误!");
exit(-1);
} else {
printf("源文件内容为:%s\n", buffer2);
if((wt1 = write(fd2, buf, sizeof(buf)))>0){
printf("写入了: %d个字节\n",wt1 );
printf("文件描述符为:%d\n", fd2);
close(fd2);
}else
{
printf("文件写入失败\n");
exit(-1);
}
}
if((fd2 =(open(path, O_RDONLY))) < 0 ) {
printf("你的test1.txt文件出现错误!");
exit(-1);
}else{
if ((size2 = read(fd2, buffer2, BUFFER_MAX)) < 0) {
printf("读取操作的size2: %d\n", size2);
printf("文件读取失败,请检查文件!\n");
exit(-1);
} else {
printf("文件内容为:%s\n", buffer2);
close(fd2);
}
}
printf("****************************************************************\n");
}
int work3(char * path1, char * path2){
printf("\n作业要求三\n");
if((fd1 = open(path1, O_RDWR)) > 0 && (size1 = read(fd1, buffer1, BUFFER_MAX)) > 0){
printf("拷贝的目标文件内容:%s\n", buffer1);
close(fd1);
}else{
printf("打开或者读取文件失败,请检查\n");
exit(-1);
}
if((fd2 = open(path2, O_RDWR)) > 0 && (size2 = read(fd2, buffer2, BUFFER_MAX)) > 0){
printf("拷贝前的源文件内容:%s\n", buffer2);
if((wt1 = write(fd2,buffer1,size1)) > 0){
printf("写入中...\n");
printf("一共写入了: %d个字节\n",wt1 );
close(fd2);
}else{
printf("文件写入失败!\n");
exit(-1);
}
if((fd2 =(open(path2, O_RDONLY))) < 0 ) {
printf("你的test1.txt文件出现错误!");
exit(-1);
}else{
if ((size2 = read(fd2, buffer2, BUFFER_MAX)) < 0) {
printf("文件读取失败,请检查文件!\n");
exit(-1);
} else {
printf("拷贝后test1文件内容为:%s\n", buffer2);
close(fd2);
}
}
}else{
printf("打开或者读取文件失败,请检查\n");
exit(-1);
}
}
网友评论