小编Ale*_*ern的帖子

优化我的read()循环C(两个循环合二为一)

我需要读取文件并将它们存储在mainbuff和mainbuff2中.

我只能使用系统调用像open(),read(),write()等等.

我不想把它们存放在堆栈中,如果它会非常大的话呢?堆分配更好.

这段代码有效:

...
    char charbuf;
    char *mainbuff1=malloc(100);
    char *mainbuff2=malloc(100);
    while (read(file1, &charbuf, 1)!=0)
            mainbuff1[len++]=charbuf;
    while (read(file2, &charbuf, 1)!=0)
            mainbuff2[len2++]=charbuf;
...
Run Code Online (Sandbox Code Playgroud)

但是mainbuff只有100个字符.更好的解决方案是在计算文件中的字符后分配mainbuff,如下所示:

...
    char charbuf;
    while (read(file1, &charbuf, 1)!=0)
            len++;
    while (read(file2, &charbuf, 1)!=0)
            len2++;
    char *mainbuff1=malloc(len);
    char *mainbuff2=malloc(len2);
...
Run Code Online (Sandbox Code Playgroud)

然后再次重复while循环并将字节读入mainbuff.

但是2个循环(第一个将读取和计数,第二个将读取)对于大型文件将是无效且缓慢的.需要在一个或更高效的其他方面做到这一点.请帮忙!不知道!

c c++ unix linux

4
推荐指数
2
解决办法
198
查看次数

stdin 到 zip 命令而不是提示

想用密码保护我的 ZIP 档案。

用这个创建存档:

zip -er archivename.zip file
Run Code Online (Sandbox Code Playgroud)

得到这个:

Enter password: 
Verify password: 
Run Code Online (Sandbox Code Playgroud)

一切正常,但我有密码变量,需要将此密码发送到zip. 尝试过这样的论点,但失败了。

echo "$1"| zip -er archivename.zip file
Run Code Online (Sandbox Code Playgroud)

在 bash 中可能吗?因为 zip 实用程序不支持stdin.

unix bash terminal zip stdin

3
推荐指数
2
解决办法
2145
查看次数

如何将char*数组保存在C中的堆栈中

char *file1charbuf=(char*)malloc(sizeof(char));
char *file2charbuf=(char*)malloc(sizeof(char));
Run Code Online (Sandbox Code Playgroud)

在循环直到EOF我读焦炭引入*file1charbuf*file2charbuf,然后比较.

...
check=read(file1, file1charbuf, 1);
check2=read(file2, file2charbuf, 1);
if (*file1charbuf!=*file2charbuf){
         printf("differ: char %i, line %i\n",charpos,linepos);
         exit(1);
}
....
Run Code Online (Sandbox Code Playgroud)

比较工作正常,但我想将指针保持在堆栈中,而不是堆中.malloc也是C lib函数.

char *file1charbuf[1]; //1 element array of char
char *file2charbuf[1];
Run Code Online (Sandbox Code Playgroud)

与那个比较不起作用

...
if (file1charbuf[0]!=file2charbuf[0]){
         printf("differ: char %i, line %i\n",charpos,linepos);
         exit(1);
}
...
Run Code Online (Sandbox Code Playgroud)

和第二个问题.是否有必要close(file1),如果exit(1)发现了什么?

  • 我应该只使用sys调用,而不是lib函数.

c c++ unix linux

0
推荐指数
1
解决办法
212
查看次数

标签 统计

unix ×3

c ×2

c++ ×2

linux ×2

bash ×1

stdin ×1

terminal ×1

zip ×1