0

我编写的代码理想情况下应该从一个文档中获取数据,对其进行加密并将其保存在另一个文档中。

但是当我尝试执行代码时,它不会将加密数据放入新文件中。它只是让它空白。有人请找出代码中缺少的内容。我试过了,但我想不通。

我认为读/写函数有问题,或者我执行的 do-while 循环不正确。

#include <stdio.h>
#include <stdlib.h>
#include <termios.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>


int main (int argc, char* argv[]) 
{
    int fdin,fdout,n,i,fd;
    char* buf;
    struct stat fs;

    if(argc<3)
        printf("USAGE: %s source-file target-file.\n",argv[0]);

    fdin=open(argv[1], O_RDONLY);
    if(fdin==-1)
        printf("ERROR: Cannot open %s.\n",argv[1]);

    fdout=open(argv[2], O_WRONLY | O_CREAT | O_EXCL, 0644);
    if(fdout==-1)
        printf("ERROR: %s already exists.\n",argv[2]);

    fstat(fd, &fs);
    n= fs.st_size;
    buf=malloc(n);

    do
    {
        n=read(fd, buf, 10);

        for(i=0;i<n;i++)
            buf[i] ^= '#';

        write(fd, buf, n);
    } while(n==10);

    close(fdin);
    close(fdout);
}
4

3 回答 3

3

您在 fstat 中使用 fd 而不是 fdin,读写系统调用。fd 是一个未初始化的变量。

于 2010-09-05T18:39:35.110 回答
2
// Here...
fstat(fd, &fs);

// And here...
n=read(fd, buf, 10);

for(i=0;i<n;i++)
    buf[i] ^= '#';

write(fd, buf, n);

你正在阅读和写作fd而不是fdinand fdout。确保启用编译器将发出的所有警告(例如 use gcc -Wall -Wextra -pedantic)。如果您允许,它将警告您使用未初始化的变量。

此外,如果您检查了、 或的返回码fstat(),您可能会因使用无效文件描述符而出错。他们很可能会因 EINVAL(无效参数)错误而出错。read()write()

fstat(fd, &fs);
n= fs.st_size;
buf=malloc(n);

既然我们在这里:分配足够的内存来保存整个文件是不必要的。您在循环中一次只读取 10 个字节,因此您实际上只需要一个 10 字节的缓冲区。你可以完全跳过fstat()

// Just allocate 10 bytes.
buf = malloc(10);

// Or heck, skip the malloc() too! Change "char *buf" to:
char buf[10];
于 2010-09-05T18:40:45.793 回答
0

所有人都说对了,还有一个提示。

您应该使用适合系统硬盘块的更大缓冲区,通常为 8192。这将显着提高您的程序速度,因为您对磁盘的访问将减少 800 倍。如您所知,访问磁盘非常昂贵时间条款。

另一种选择是使用 stdio 函数 fread、fwrite 等,它们已经负责缓冲,但您仍然会有函数调用开销。罗尼

于 2010-09-05T21:19:44.747 回答