c - 文件打开成功但读取结果为 "Bad file descriptor"错误并且统计显示文件大小为零

标签 c linux

我正在做一项作业,我们应该对使用较差的加密算法加密的 PDF 进行加密分析。

教授提供的代码使用 fd=open(filename, O_CREAT|O_WRONLY, S_IRUSR|S_IWUSR) 创建加密文件。

在我尝试解密的代码中,我使用 fd_in=open(file, O_RDONLY) 打开该文件。

问题是,当我尝试从文件中读入时,出现“文件描述符错误”错误。我使用 stat 来尝试获取有关文件描述符对已打开文件的“想法”的更多信息,它显示文件的长度为 0,而实际上它只有几百 KB。

我使用的调试代码是:

if (0 > (len = read(fd_in, (char*)&read_buff, BITE))) {    // BITE is defined as 8
  printf("Error occured grabbing first bite of %s.\n", file);
  printf("%s.\n", strerror(errno));

  struct stat fileStat;
  int stat = fstat(fd_in, &fileStat);

  printf("fstat returned: %d.\n", stat);      // Consistently printing 0
  printf("Information for %s\n",file);
  printf("---------------------------\n");
  printf("File Size: \t\t%d bytes\n",fileStat.st_size);
  printf("Number of Links: \t%d\n",fileStat.st_nlink);
  printf("File inode: \t\t%d\n",fileStat.st_ino);

  printf("File Permissions: \t");
  printf( (S_ISDIR(fileStat.st_mode)) ? "d" : "-");
  printf( (fileStat.st_mode & S_IRUSR) ? "r" : "-");
  printf( (fileStat.st_mode & S_IWUSR) ? "w" : "-");
  printf( (fileStat.st_mode & S_IXUSR) ? "x" : "-");
  printf( (fileStat.st_mode & S_IRGRP) ? "r" : "-");
  printf( (fileStat.st_mode & S_IWGRP) ? "w" : "-");
  printf( (fileStat.st_mode & S_IXGRP) ? "x" : "-");
  printf( (fileStat.st_mode & S_IROTH) ? "r" : "-");
  printf( (fileStat.st_mode & S_IWOTH) ? "w" : "-");
  printf( (fileStat.st_mode & S_IXOTH) ? "x" : "-");
  printf("\n\n");

  return 1;

我得到的结果是:

Error occured grabbing first bite of enc.pdf.
Bad file descriptor.
Information for enc.pdf
---------------------------
File Size:      0 bytes
Number of Links:    1
File inode:         16441996
File Permissions:   -rw-------

ls 报告文件为

-rw-------  1 matt  matt   157887 Oct 29 03:01 enc.pdf

打开文件相关代码:

int fd_in=open(file, O_RDONLY);
if(fd_in<0) {
   printf("Failed to open the input file %s.\n", file);
   return 1;
} else {
    printf("File open, descriptor is: %d.\n", fd_in);
}

这一直打印出已归档描述符的值 3。

有一些关于read_buff的问题。加密/解密过程涉及对读取的值进行异或运算。因此,缓冲区被声明为 unsigned long long,为了读入它,我获取地址并将其转换为 (char*)。这种策略直接来自教授创建加密文件的代码。

我什至添加了一个带有 printf 的 else 来验证文件描述符是否有效。目前它似乎始终是 3 这绝对不是 -1

最佳答案

您可能想检查堆栈是否在调用 open()read() 之间损坏,以便文件描述符 fd_in 将被更改。

关于c - 文件打开成功但读取结果为 "Bad file descriptor"错误并且统计显示文件大小为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13118274/

相关文章:

用于开发的 Linux

c - 在最近的 Linux 内核上测试 msync 使用的好方法是什么?

c - 如何统计树遍历的函数调用次数

c - 在 C 程序中获取段错误

json - Ajax 调用以检索 json 文件数据

windows - 基于操作系统的C++条件编译

c++ - 保存时格式化 C/C++ 代码

c - 为什么字节序在一个字节中的位之间很重要?

php - 如何识别两个相同的 nohup 命令?

linux - bash 中的 "batch"文件