Linux下C语言的文件操作

时间:2021-08-03 05:14:20

代码:

 #include <stdio.h>
#include <string.h>
#include <fcntl.h>
/*************基本的函数API********************
int open(const char *pathname, int oflag, int perms)
oflag:
O_RDONLY 只读
O_WRONLY 只写
O_RDWR 读写
O_APPEND 追加
O_CREAT 创建
O_EXCL 测试
O_TRUNC 删除
perms:
被打开的文件的存取权限,采用8进制
int close(int fd)
ssize_t read(int fd, void *buf, size_t count)
fd:
文件描述符
buf:
指定存储器读取数据的缓冲区
count:
指定读取数据的字节数
ssize_t write(int fd, void *buf, size_t count)
fd:
文件描述符
buf:
指定存储器读取数据的缓冲区
count:
指定读取数据的字节数
off_t lseek(int fd, off_t offset, int whence)
fd:
文件描述符
offset:
偏移量,每一读写操作需要移动的字节数,可向前、可向后
count:
当前位置的基点:
SEEK_SET(当前位置是文件的开头)
SEEK_CUR(当前位置为文件指针的位置,新位置为当前位置加上偏移量)
SEEK_END(当前位置问文件的尾部,新位置为文件大小加上偏移量的大小)
**********************************************/
int main(void)
{
int fd,len;
char *buf = "Hello World!\n",Out[];
fd = open("a.txt", O_CREAT | O_TRUNC | O_RDWR, );
printf("open file:a.txt fd = %d\n", fd);
len = strlen(buf);
int size = write(fd, buf, len);
close(fd);
//Begin to read the file
fd = open("a.txt", O_RDWR, );
lseek(fd, , SEEK_SET); //Before to read the file,you should call the function to make the fd point to begin of files
size = read(fd, Out, );
printf("size = %d\nread from file:\n %s\n",size,Out);
close(fd);
return ;
}

实例1   读取一张通过MATLAB读取JPG图片转换成TXT文本的文件内容:

首先图像是这样的lena.jpg:

Linux下C语言的文件操作      Linux下C语言的文件操作

通过MATALB读取进去之后,转换成灰度图像,如下所示处理结果如上图所示:

I = imread('F:\Leanring\C\Learning\lena.jpg');
Gray = rgb2gray(I);
imshow(Gray)

接下来我们在变量一栏中,复制粘贴所有的数据到TXT文本当中,如下所示:

                        MATLAB数据                                                          文本数据

Linux下C语言的文件操作   Linux下C语言的文件操作

这样,我们通过分析文本中的数据分布格式,首先,文本挡住的所有数据都是只包含了图像的数据的,不包括了JPG图片格式相关的数据内容,其次,在我们复制粘贴的过程中的每两个数据之间的分隔方式都是通过TAB键来分隔的,同样的在每一行数据的结尾部分,都是通过回车键\t或者换行符\n来结尾的,所以根据这样的数据格式,我们设计如下的读取对应文本内容的C语言函数API,这里的TAB在ASCII的编码数据是:9 同样的,\t和\n的ASCII的编码是10和13,这样的话,通过if就能隔离开数据。

void ImageReadFromTXT(int *data,int width,int height,char *dir)
{
FILE *Pic;
int D=,count=,Bit[]={},i,j;
Pic = fopen(dir,"rb");
for(i=;i<height;i++)
{
D = ;
for(j=;j<width;j++)
{
count = ;
Bit[] = ;
Bit[] = ;
Bit[] = ;
D = ;
while()
{
fread(&D,sizeof(char),,Pic);
if(D == || D == || D == ) break;// D == 9
Bit[count] = D-;
count++;
}
*(data+i*width+j) = Bit[]*+Bit[]*+Bit[];
}
}
fclose(Pic);
}

主函数内容如下:

 /***********************************************************
从TXT文件中读取一个图片文件的数据,图片文件的数据首先通过
MATLAB读取到变量中,然后复制粘贴到TXT文件当中处理。
***********************************************************/
int width=;
int height =;
int data[width][height];
ImageReadFromTXT(data,width,height,"lena.txt");
printf("The first data is:%d\n",data[][]);
printf("The first data is:%d\n",data[][]);
printf("The first data is:%d\n",data[][]);
printf("The first data is:%d\n",data[][]);

实验结果:

Linux下C语言的文件操作