如何在不使用 stdio.h 库的情况下读写文件?
How read and write from a file without using the stdio.h library?
上下文:这是考试学习指南上的一道题。
Question: Write a piece of code that uses the low-level Unix I/O system calls (not stdio or iostreams) that does the following:
o Open a file named "data.txt" for reading.
o Read up to 512 bytes from the file into an array named buf.
o Close the file.
如果任何一步出错,打印错误信息并退出程序。
包括您的代码使用的任何变量的定义。
我在 linux 环境中使用 c
语言的 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<stdio.h>
的情况下翻译上述代码?
问题说要使用 UNIX 低级 I/O 例程。这些都在 unistd.h 中定义,因此您将需要 #include <unistd.h>
,然后需要调用其中定义的 open
、read
和 close
。
你需要的函数被称为open()
(来自<fcntl.h>
),read()
(来自<unistd.h>
)和close()
(来自<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);
上下文:这是考试学习指南上的一道题。
Question: Write a piece of code that uses the low-level Unix I/O system calls (not stdio or iostreams) that does the following:
o Open a file named "data.txt" for reading.
o Read up to 512 bytes from the file into an array named buf.
o Close the file.
如果任何一步出错,打印错误信息并退出程序。 包括您的代码使用的任何变量的定义。
我在 linux 环境中使用 c
语言的 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<stdio.h>
的情况下翻译上述代码?
问题说要使用 UNIX 低级 I/O 例程。这些都在 unistd.h 中定义,因此您将需要 #include <unistd.h>
,然后需要调用其中定义的 open
、read
和 close
。
你需要的函数被称为open()
(来自<fcntl.h>
),read()
(来自<unistd.h>
)和close()
(来自<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);