C - 不使用iostream读取文件

时间:2010-12-19 18:37:19

标签: c iostream

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

4 个答案:

答案 0 :(得分:3)

您是在谈论C ++(有标题<iostream>)还是关于C,您可能正在谈论文件流,又名FILE *,如<stdio.h>中所见(或,在C ++中,在<cstdio>)?

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

  • 靠近
  • lseek的

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

答案 1 :(得分:1)

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

答案 2 :(得分:1)

您可以将内存映射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 :(得分:1)

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

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
}
相关问题