找回密码
 加入
搜索
查看: 2006|回复: 3

会C++的朋友帮个忙啊,读文件到内存的问题。

[复制链接]
发表于 2009-2-27 10:58:51 | 显示全部楼层 |阅读模式
FILE *fp;

if(!(fp=fopen(filename,"rb")))
    {
    printf("Cannot open '%s' for reading. Exit.\n",filename);
    exit(1);
    }

/* get file size */

fseek (fp, 0, SEEK_END);
filesize = ftell(fp);
fseek (fp, 0, SEEK_SET);

/* read file in buf */

buf = (unsigned char *) malloc(filesize+1);
if(!buf)
    {
    printf("Cannot allocate %lu bytes. Exit.\n",filesize);
    exit(1);
    }
unsigned long int readed=fread(buf,1,filesize,fp);
if(readed!=filesize)
    {
    printf("By some reason i cant read '%s'. I want to read %lu bytes, but can read only %lu bytes.Exit.\n", filename, filesize, readed);
    exit(1);
    }
fclose(fp);

if(debug)printf("File read complete\n");
我不会C++,但是看代码,这段代码是将一个文件读到内存。如果用autoit重现这个过程呢?

我用fileread和_FileReadToArray,结果都不对。

大家帮忙看看。
发表于 2009-2-27 22:34:31 | 显示全部楼层
fopen(filename,"rb")表示读取文件的二进制值,在au3下面是FileOpen($File, 4)或者把4替换成32、64等
至于剩下的代码,就是读取时会出现的错误,在au3下,如果读取错误,@error值会改变,所以没有办法对应上面的代码一一翻译

au3本来就是将文件读入内存,因为au3是脚本,所以C里面关于内存分配纠错部分的代码你就不用操心了

[ 本帖最后由 xinlu8439 于 2009-2-27 22:36 编辑 ]
 楼主| 发表于 2009-2-28 10:12:01 | 显示全部楼层
[au3]
$smsfile="MessagesDatabase.pdb"

$file=FileOpen($smsfile,128)

$buf=FileRead($file)
ConsoleWrite(IsArray($buf)&'|'&IsHWnd($buf)&'|'&IsPtr($buf)&'|'&IsBinary($buf)&'|'&IsString($buf))
ConsoleWrite($buf)


$filesize=FileGetSize($smsfile)
ConsoleWrite($filesize)
$i=0
Do
        ConsoleWrite($buf[$i])
        $i+=1
Until $i<($filesize-6)

FileClose($file)


[/au3]

其中不论fileopen用什么参数,类型都是string型的。

我想把这个文件读成每个字节形式的数组,即 Array[0]-Array[$filesize-1]形式,怎么办呢?

[ 本帖最后由 zerozha 于 2009-2-28 10:21 编辑 ]
 楼主| 发表于 2009-2-28 13:19:05 | 显示全部楼层
[au3]
$smsfile = "MessagesDatabase.pdb"

$file = FileOpen($smsfile, 16)
$tmpbuf = FileRead($file)

$filesize = BinaryLen($tmpbuf)
ConsoleWrite($filesize & @CRLF)

Dim $buf[$filesize]
For $j=0 to $filesize-1
$buf[$j]=BinaryMid($tmpbuf,$j,1)
ConsoleWrite($buf[$j]& @CRLF)
Next

ConsoleWrite("Done" & @CRLF)

$i = 0
Do
        If ($buf[$i] == 0x1B) And ($buf[$i + 1] == 0x54) And ($buf[$i + 2] == 0x72) And ($buf[$i + 3] == 0x53) And ($buf[$i + 4] == 0x4D) Then
                ConsoleWrite($i& @CRLF)
        EndIf

        $i += 1
Until $i < ($filesize - 6)
FileClose($file)

[/au3]

发现这一步
[au3]Dim $buf[$filesize]
For $j=0 to $filesize-1
$buf[$j]=BinaryMid($tmpbuf,$j,1)
ConsoleWrite($buf[$j]& @CRLF)
Next
[/au3]
要耗费很长的时间,文件长度为1M多,要生成100万多个值,真的很恐怖。

我想做的是用autoit3重写这段代码。有高手愿意看看吗》?

[ 本帖最后由 zerozha 于 2009-2-28 16:03 编辑 ]

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?加入

×
您需要登录后才可以回帖 登录 | 加入

本版积分规则

QQ|手机版|小黑屋|AUTOIT CN ( 鲁ICP备19019924号-1 )谷歌 百度

GMT+8, 2024-9-23 07:27 , Processed in 0.074901 second(s), 22 queries .

Powered by Discuz! X3.5 Licensed

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表