背景:这是关于考试学习指南的问题.
问题:编写一段代码,该代码使用执行以下操作的低级Unix I/O系统调用(不是stdio或iostream):
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);
}
}
Run Code Online (Sandbox Code Playgroud)
如何在不使用库的情况下将上述代码翻译成工作#include<stdio.h>?
您需要的函数称为open()(from <fcntl.h>),read()(from <unistd.h>)和close()(from <unistd.h>).这是一个用法示例:
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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1750 次 |
| 最近记录: |