【问题标题】:How read and write from a file without using the stdio.h library?如何在不使用 stdio.h 库的情况下从文件中读取和写入?
【发布时间】:2016-04-27 06:08:24
【问题描述】:

上下文:这是一个关于考试学习指南的问题。

问题:编写一段代码,使用低级 Unix I/O 系统调用(不是 stdio 或 iostreams)执行以下操作:

o 打开一个名为“data.txt”的文件进行读取。

o 从文件中读取最多 512 个字节到名为 buf 的数组中。

o 关闭文件。

如果在任何步骤中出现错误,请打印错误消息并退出程序。 包括代码使用的任何变量的定义。

我在c 语言的Linux 环境中使用pico IDE。我知道如何使用#include <stdio.h> 轻松做到这一点,但我不知道没有它我将如何编写代码。现在我目前有:

#include <stdio.h>

int main()
{
 // File var
 FILE *fileVar;
 char buff[512];

 // Open it
 fileVar = fopen("data.txt", "r");

 // Check for error
 if(fileVar == NULL)
 {
   perror("Error is: ");
 }
 else
 {
   fscanf(fileVar, "%s", buff);
   printf("The file contains:  %s\n", buff);
   fgets(buff, 512, (FILE*)fileVar);
   fclose(fileVar);
 }

}

如何在不使用库#include&lt;stdio.h&gt; 的情况下翻译上述代码?

【问题讨论】:

  • 大概是你在课堂上学到的东西?

标签: c readfile


【解决方案1】:

您需要的函数称为open()(来自&lt;fcntl.h&gt;)、read()(来自&lt;unistd.h&gt;)和close()(来自&lt;unistd.h&gt;)。这是一个使用示例:

fd = open("input_file", O_RDONLY);
if (fd == -1) {
    /* error handling here */
}

count = read(fd, buf, 512);
if (count == -1) {
    /* error handling here */
}

close(fd);

【讨论】:

  • 没有close() 的错误句柄?也许你伤害了close()的感情?
  • @chux 我认为在这种情况下忽略close() 上的错误是安全的,因为我们没有写入文件。
  • close()fclose() get no respect。 ;-)
【解决方案2】:

问题说要使用 UNIX 低级 I/O 例程。这些都在 unistd.h 中定义,因此您需要 #include &lt;unistd.h&gt;,然后需要调用其中定义的 openreadclose

【讨论】:

  • 这个答案很简短。它可能应该是评论或扩展。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-02-02
  • 2023-01-02
  • 2016-04-14
  • 2023-03-28
  • 1970-01-01
  • 2017-09-19
  • 2011-02-11
相关资源
最近更新 更多