简体   繁体   English

我如何从C中的文件中读取

[英]How can i read from a file in C

How do I read from a file using this function?如何使用此功能从文件中读取?

#include <stdio.h>

char* read_from_file (const char* filename, size_t length)
{
  //I have this so far
  fp = fopen(filename,"r"); // read mode

  if( fp == NULL )
  {
      perror("Error while opening the file.\n");
      exit(EXIT_FAILURE);
  }

  /* what goes in here? */

  return NULL;
}

I'm trying to implement to the following guidelines:我正在尝试实施以下准则:

  • It allocates a char buffer of size length+1.它分配一个长度为+1 的字符缓冲区。

  • It opens file filename, in read only mode.它以只读模式打开文件 filename。 When it fails to open the file, it deallocates the buffer memory当它无法打开文件时,它会释放缓冲内存

  • It reads length characters into the buffer, inserts a null character (\\0) in the last position, closes the file and returns a pointer to the buffer.它将 length 个字符读入缓冲区,在最后一个位置插入一个空字符 (\\0),关闭文件并返回一个指向缓冲区的指针。 When it fails to read length characters, it deallocates the buffer memory, closes the file and returns NULL.当读取 length 个字符失败时,它释放缓冲内存,关闭文件并返回 NULL。

You pretty much included the answer in your question:您几乎在问题中包含了答案:

  1. Allocate a char buffer of size length +1.分配一个length +1 的字符缓冲区。

  2. Open the file filename , in read only mode.以只读模式打开文件filename If you fail to open the file, deallocate the buffer and return如果打开文件失败,释放缓冲区并返回

  3. Read length characters into the buffer, inserts a null character (\\0) in the last position, close the file and return a pointer to the buffer.length字符读入缓冲区,在最后位置插入一个空字符 (\\0),关闭文件并返回指向缓冲区的指针。

  4. If you fail to read length characters, deallocate the buffer memory, close the file, and return NULL.如果读取length字符失败,则释放缓冲内存,关闭文件,并返回 NULL。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM