对文件的操作方法

在C中可以利用函数open , read, write, close来实现对文件的打开, 读写, 关闭的操作

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

int main(void)
{
        int fd = -1; 
        ssize_t size = -1; 
        unsigned char buf[10] = {0};
        char filename[] = "test.txt";
        char buf1[] = "this is a test!";
        int i = 0;

        fd = open(filename, O_RDWR);/*打开文件*/
        if( -1 == fd) {
                printf("Open file %s failure, fd:%d\n", filename, fd);
        } else {
                printf("Open file %s success, fd:%d\n", filename, fd);
        }   

        while(size){
                size = read(fd, buf,10);/*读出文件中的10个字符*/
                if(-1 == size) {
                        close(fd);
                        printf("read file erro occurs\n");
                        return -1; 
                } else {
                        if(size > 0) {
                                printf("read %ld bytes:", size);
                                printf("\"");
                                for(i = 0; i < size; i++){
                                  if(*(buf+i) != 0x0a)
                                  printf("%c", *(buf + i));
                                }
                                printf("\"\n");
                                bzero(buf, 10);/*每次使用完buf,清空。可以保证对下次的使用没有干扰*/
                        } else {
                                printf("reac the end of file\n");
                        }
                }
        }
        size = write(fd, buf1, strlen(buf1));
        printf("write %ld byted to file\n", size);
        close(fd);
        return 0;
} 

在文件test.txt中写入一行数子1122334455667788

执行结果

kayshi@ubuntu:~/code/file$ ./file 
Open file test.txt success, fd:3
read 10 bytes:"1122334455"
read 7 bytes:"667788"
reac the end of file
write 15 byted to file
kayshi@ubuntu:~/code/file$ 

执行完后test.txt中的信息

1122334455667788
this is a test!

注意:1. read函数会把文件中的所有内容当做一行来处理,如果文中有换行符,就会把换行符当做一个字符。这就是上面的第二次读的时候,其实只剩了6个字符。却读出7个。这是因为有一个是换行符。ascii码为0x0a ,我在代码中,做了处理,如果是换行符就不打印。
2. 使用write函数向文件中写入数据,再读的时候结尾是没有换行符的。第一行有换行符,应该是编译器自带的功能

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值