一.使用不带缓存的IO函数对文件进行修改
由于需要在工作中将前向推理框架中的卷积算子量化成int8类型,需要对每个卷积层进行量化。但是由于提供的量化表中的每个数据以空格隔开,我需要将量化表中的量化系数以数组类型进行组织,人工添加逗号,工作量太大。所以写了个C程序将量化表中的量化系数之间全部以逗号隔开,后面直接将系数复制到程序中即可。虽然直接读取文件并加载进内容更方便,但此举也是顺便复习一下C语言中的IO函数使用。
程序功能:
1.获取文件大小(字节数)
2.将文件中所有的空格替换成逗号,并输出到.txt文件中
二.程序源码
#include<stdio.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
/*使用系统调用io函数进行文件操作
**将文件中所有的空格字符替换为‘,’,并输出到1.txt文件中
*/
void showlog(char *argv[])
{
printf("Usage:%s [filename]\n",argv[0]);
}
/*获取文件所占字节数函数*/
int get_file_bytes(char* argv[])
{
struct stat statbuf; //设置stat结构体变量
stat(argv[1],&statbuf);
int size=statbuf.st_size; //获得文件字节数
return size;
}
int main(int argc,char *argv[])
{
int flag1; //文件描述符
int flag2;
int index1=0;
int index2=0;
int size_bytes; //存储文件字节数
int size1; //存储读入的文件字节数
int size2; //存储写入的文件字节数
if(argc!=2)
showlog(argv);
else
{
flag1=open(argv[1],O_RDONLY); //打开文件
flag2=open("1.txt",O_WRONLY|O_CREAT,0755); //创建1.txt文件
size_bytes=get_file_bytes(argv); //获取输入文件字节数
char buffer1[size_bytes];
char buffer2[size_bytes];
if(flag1>=0&&flag2>=0)
{
printf("Open file and creat 1.txt success\n");
printf("The file size is %d bytes\n",size_bytes);
size1 = read(flag1,buffer1,size_bytes); //读取输入文件,返回读取的字节数
if(size1!=0)
{
printf("Read file success and read bytes:%d\n",size1);
for(int i=0;i<size_bytes;i++)
{
buffer2[index2]=buffer1[index1];
if(buffer1[index1] == 32)
{
buffer2[index2] = ',' ;
}
index1++;
index2++;
}
size2 = write(flag2,buffer2,size_bytes); //将buffer2内容写入到1.txt文件中
printf("Write file success and write bytes:%d\n",size2);
close(flag1); //关闭文件1
close(flag2); //关闭文件2
}
else
{
printf("File is empty or EOF\n");
}
}
else
{
printf("Open file failed\n");
}
}
return 0;
}