[英]Problem in code with File Descriptors. C (Linux)
我编写的代码理想上应该从一个文档中获取数据,对其进行加密并将其保存在另一文档中。
但是,当我尝试执行代码时,不会将加密的数据放入新文件中。 它只是空白。 有人请找出代码中缺少的内容。 我尝试过,但我不知道。
我认为读/写功能有问题,或者我执行的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);
}
您在fstat中使用fd而不是fdin来读写系统调用。 fd是未初始化的变量。
// Here...
fstat(fd, &fs);
// And here...
n=read(fd, buf, 10);
for(i=0;i<n;i++)
buf[i] ^= '#';
write(fd, buf, n);
您正在读写fd
而不是fdin
和fdout
。 确保启用了编译器将发出的所有警告(例如,使用gcc -Wall -Wextra -pedantic
)。 如果您允许使用它,它将警告您使用未初始化的变量。
另外,如果您检查了fstat()
, read()
或write()
的返回码, fstat()
使用无效的文件描述符可能会出错。 它们很可能会因EINVAL(无效参数)错误而出错。
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];
所有人都说得对,还有一个提示。
您应该使用适合系统硬盘块的较大缓冲区,通常为8192。这将显着提高程序速度,因为对磁盘的访问将减少800倍。如您所知,在Windows中访问磁盘非常昂贵时间条款。
另一个选择是使用stdio函数fread,fwrite等,它们已经处理了缓冲,但仍然会有函数调用开销。 罗尼
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.