Linux 下 C语言大文件读写(大于4G)
以下的做法整理自论坛上的帖子。
如何create大文件
要大就非常大,1T吧。
有两种方法:
一.dd
dd if=/dev/zero of=1T.img bs=1G seek=1024 count=0
bs=1G表示每一次读写1G数据,count=0表示读写0次,seek=1024表示略过1024个Block不写,前面block size是1G,所以共略过1T!
这是创建大型sparse文件最简单的方法。
二.ftruncate64/ftruncate
如果用系统函数就稍微有些麻烦,因为涉及到宏的问题。我会结合一个实际例子详细说明,其中OPTION标志的就是测试项。
文件sparse.c:
//OPTION 1:是否定义与大文件相关的宏
#define _LARGEFILE_SOURCE
#define _LARGEFILE64_SOURCE
#define _FILE_OFFSET_BITS 64
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#define FILENAME "bigfile"
#define FILE_MODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)
int main(int argc, char **argv)
{
int fd, ret;
off_t offset;
int total = 0;
if ( argc >= 2 )
{
total = atol(argv[1]);
printf("total=%d\n", total);
}
//OPTION 2:是否有O_LARGEFILE选项
//fd = open(FILENAME, O_RDWR|O_CREAT|O_LARGEFILE, 0644);
fd = open(FILENAME, O_RDWR|O_CREAT, 0644);
if (fd < 0) {
perror(FILENAME);
return -1;
}
offset = (off_t)total *1024ll*1024ll*1024ll;
printf("offset=%ld\n", offset);
//OPTION 3:是否调用64位系统函数
//if (ftruncate64(fd, offset) < 0)
if (ftruncate(fd, offset) < 0)
{
printf("[%d]-ftruncate64 error: %s\n", errno, strerror(errno));
close(fd);
return 0;
}
close(fd);
printf("OK\n");
return 0;
}
测试环境:
linux:/disk/test/big # gcc --version
gcc (GCC) 3.3.5 20050117 (prerelease) (SUSE Linux)
linux:/disk/test/big # uname -a
Linux linux 2.6.11.4-20a-default #1 Wed Mar 23 21:52:37 UTC 2005 i686 i686 i386 GNU/Linux
测试结果
相关文档:
由于 Linux 良好的用户权限管理体系,病毒往往是 Linux 系统管理员最后才需要考虑的问题。以往,Linux 上的杀毒软件主要是为企业的邮件和文件服务器所设计的。如今,随着 Linux 桌面用户数量的增长,桌面用户在受益于 Linux 系统对病毒较强的天然免疫力的同时,也需要杀毒软件清理从网络或U盘带来的WIndows病毒。尽管那些 ......
在实现驱动程序的mmap函数时,要注意映射地址的转换问题,见代码。
定义一个设备结构体:
struct leedriver
{
struct cdev cdev;
unsigned char mem[MEMSIZE];
};
这里面这个MEMSIZE,最小都要是4096,因为内存映射是以页为单位的。
在实现simple_remap_mmap函数时,代码如下
static int simple_remap_mmap(stru ......
pid_t pid=fork()
it has 3 situation for the return result pid
0 child
>0 parent process
<0 fork fail
fork create a new process and it parent live alse when the child process had been created ......
在此摘录C编译时出现的警告信息的意义。
1) warning: ISO C90 forbids mixed declarations and code
C语言是面向过程的语言,这个警告通常表示声明应该在其他代码的前面。
2) warning: initialization from incompatible pointer type
在Linux kernel中有许多callback函数,这个警告表明callback函数的实现中,或者返 ......
#include <iostream>
#include <conio.h>
using namespace std;
typedef struct _INTTEST
{
int a;
}inttest;
int main()
{
inttest* p=new inttest[3];
p[1].a=10;
cou ......