【问题标题】:C - Read a file without using iostreamC - 不使用 iostream 读取文件
【发布时间】:2011-05-27 22:26:24
【问题描述】:

假设我有一个文件 SomFoo.txt,其中包含一定长度的字符串。 有没有不使用 iostream 即(fread 或 fgets)来读取文件内容的方法。 我知道文件的大小。

【问题讨论】:

  • fgetc/fgets/fread/read 是读取文件的函数!读取使用文件描述符其他功能使用文件指针。您是说要使用文件描述符而不是文件指针吗?也许如果你解释得更好 - 你可能会得到更好的答案。还要识别操作系统。
  • C 没有iostream。我认为您需要编辑标签。

标签: c iostream


【解决方案1】:

您是在谈论 C++(其中有一个标头 <iostream>)还是在谈论 C,您可能在谈论文件流,也就是 FILE *,如在 <stdio.h>(或者,在 C++ 中,在 @ 987654324@)?

无论哪种方式,在 Unix 和相关系统上,都有许多系统调用使用比流函数更低级别的文件描述符。关键的、基本的有:

  • 打开
  • 关闭
  • 阅读
  • 寻找

还有大量其他用于专门操作(套接字、管道、异步 I/O、分散/收集 I/O、定位 I/O 等)。

【讨论】:

    【解决方案2】:

    您可以将内存映射 io 与 mmap 一起使用。下面是读取文件 /etc/fedora-release 并打印其内容的示例:

    #include <sys/mman.h>
    #include <sys/stat.h>
    #include <fcntl.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <unistd.h>
    
    #define handle_error(_label, _text) do { perror(_text); goto _label; } while (0)
    
    int main(int argc, char *argv[])
    {
        char *addr;
        int fd;
        struct stat sb;
        size_t length;
        ssize_t s;
    
        fd = open("/etc/fedora-release", O_RDONLY);
        if (fd == -1) {
            handle_error(exit_failure, "open");
        }
    
        if (fstat(fd, &sb) == -1) {
            handle_error(exit_failure, "fstat");
        }
        length = sb.st_size;
    
        addr = mmap(NULL, length, PROT_READ, MAP_PRIVATE, fd, 0);
        if (addr == MAP_FAILED) {
            handle_error(exit_failure, "mmap");
        }
    
        s = write(STDOUT_FILENO, addr, length);
        if (s != length) {
            if (s == -1) {
                handle_error(exit_failure, "write");
            }
    
            fprintf(stderr, "partial write");
            goto exit_failure;
        }
    
        exit(EXIT_SUCCESS);
    
    exit_failure:
        exit(EXIT_FAILURE);
    }
    

    【讨论】:

      【解决方案3】:

      让我们寻找一个简单的解决方案:

      int File_read(char *filename, char *buffer){
          FILE *fp = fopen(filename, "rb"); //open the file
          if (fp == NULL){
              return 0; //indicate that the file does not exist
          }
          int length = 0;
          while ((current = fgetc(fp)) != EOF){ //get one char (note return value is an int)
              buffer[length] = current; //store the current char
              length = length + 1; //increase length
          }
          fclose(fp); //close the file
          return length; //no more chars, return length
      }
      

      【讨论】:

        【解决方案4】:

        您可以在 C 代码中使用嵌入式汇编代码。

        【讨论】:

        • 是的,链接中提到了 Linux 的差异。但这是相同的基本思想。
        • INT 21 是古老的 16 位 DOS API。我不会指望今天剩下的便携式设备。他们不是删除了 64 位版本的 Windows 中的所有 DOS 支持吗?
        • 我将删除糟糕的示例,并将 Assembly 的“想法”留在 C 代码中
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-13
        • 1970-01-01
        • 1970-01-01
        • 2018-05-24
        相关资源
        最近更新 更多