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
测试结果
相关文档:
2009 年 4 月 23 日
本文中我们针对 Linux 上多线程编程的主要特性总结出 5 条经验,用以改善 Linux 多线程编程的习惯和避免其中的开发陷阱。在本文中,我们穿插一些 Windows 的编程用例用以对比 Linux 特性,以加深读者印象。
背景
Linux 平台上的多线程程序开发相对应其他平台(比如 Windows)的多线程 API 有一些细微 ......
在实现驱动程序的mmap函数时,要注意映射地址的转换问题,见代码。
定义一个设备结构体:
struct leedriver
{
struct cdev cdev;
unsigned char mem[MEMSIZE];
};
这里面这个MEMSIZE,最小都要是4096,因为内存映射是以页为单位的。
在实现simple_remap_mmap函数时,代码如下
static int simple_remap_mmap(stru ......
网上一道金山的面试题:
http://topic.csdn.net/u/20100524/14/0eff992a-2849-4db6-bdaa-d4a200e79b7c.html
请分别用C++的面向对象和泛型机制,编写实现Template Method模式的示例代码,并比较两种方式各自的优缺点。
用虚函数实现Template Method的方式就不多说了。用泛型的方式实现多态在ATL里面有大量的用到!
泛型� ......
本文以加法为例:[code]
//----------------------------------------------------
//adder.c
//---------------------------------------------------
void adder(int a, int b, int *sum)
{
*sum = a + b;
}
[/code][size=3]
[/size]
HLS工具(AutoPilot)综合之后的结� ......
; 编译链接方法
; (ld 的‘-s’选项意为“strip all”)
; gcc -c not link
;
; [root@XXX XXX]# nasm -f elf foo.asm -o foo.o
; [root@XXX XXX]# gcc -c bar.c -o bar.o
; [root@XXX XXX]# ld -s foo.o bar.o -o foobar
; [root@XXX XXX]# ./foobar
; the 2nd one
; [root@XXX XXX]#
exter ......