c - read(2) 如何与回车交互?

标签 c windows file io

我正在编写一个简单的程序来翻转文件中的所有位,但现在它只处理前 1000 个字节,直到我完成那么多工作。为什么我调用 read() 会忽略\r 字符?当我在仅包含\r\n\r\n 的文件上运行此代码时,读取调用返回 2 并且缓冲区包含\n\n。\r 字符被完全忽略。我在 Windows 上运行它(这在 Linux 机器上什至不是问题)

为什么 read(2) 在找到\r 字符时会跳过它?或者这就是正在发生的事情?

编辑:结论是 Windows 默认以“文本”模式而不是“二进制”模式打开文件。为此,调用open时,必须指定O_BINARY为模式。

谢谢,下面的代码。

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

void invertBytes(size_t amount, char* buffer);

int main(int argv, char** argc)
{
   int fileCount = 1;
   char* fileName;
   int fd = 0;
   size_t bufSize = 1000;
   size_t amountRead = 0;
   char* text;
   int offset = 0;

   if(argv <= 1)
   {
      printf("Usages: encode [filenames...]\n");
      return 0;
   }

   text = (char *)malloc(sizeof(char) * bufSize);

   for(fileCount = 1; fileCount < argv; fileCount++)
   {
      fileName = argc[fileCount];
      fd = open(fileName, O_RDWR);
      printf("fd: %d\n", fd);
      amountRead = read(fd, (void *)text, bufSize);
      printf("Amount read: %d\n", amountRead);
      invertBytes(amountRead, text);
      offset = (int)lseek(fd, 0, SEEK_SET);
      printf("Lseek to %d\n", offset);
      offset = write(fd, text, amountRead);
      printf("write returned %d\n", offset);
      close(fd);
   }

   return 0;
}

void invertBytes(size_t amount, char* buffer)
{
   int byteCount = 0;
   printf("amount: %d\n", amount);
   for(byteCount = 0; byteCount < amount; byteCount++)
   {
      printf("%x, ", buffer[byteCount]);
      buffer[byteCount] = ~buffer[byteCount];
      printf("%x\r\n", buffer[byteCount]);
   }
   printf("byteCount: %d\n", byteCount);
}

最佳答案

fd = open(fileName, O_RDWR);

应该是

fd = open(fileName, O_RDWR | O_BINARY);

参见 read() only reads a few bytes from file了解详情。

关于c - read(2) 如何与回车交互?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8764046/

相关文章:

c - 如何在C中交换文件中的元素

c - 如何使用struct向堆排序插入元素

javascript - 服务器上的 PhantomJS - PHP exec 无法 fork

.net - 在不使用大量内存的情况下显示大文件的最佳方法是什么?

c++ - 在 C 中初始化一个 char 数组。哪种方式更好?

windows - 检测 .bat 文件是否在为其分配的控制台中启动

windows - 如何知道 IEEE 1394 (FireWire) 是否连接到我的 Windows 7?

java FileNotFoundException 打开的文件太多

file - sed 如何读入和处理未知长度的文件

c - 具有结构数组的共享内存