Я использовал syscalls read() и write() в моей программе БЕЗ, включая заголовочный файл unistd.h в программе. Но все же программа работает и дает ожидаемые результаты.Как я могу использовать read() и write() без включения «unistd.h»?
После запуска программы я подумал, что прочитаю справочную страницу для read() и write().
На странице man 2 для read() и write() в разделе SYNOPSIS упоминается, что мне нужно включить заголовочный файл unistd.h для использования read() или write().
SYNOPSIS
#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);
SYNOPSIS
#include <unistd.h>
ssize_t write(int fd, const void *buf, size_t count);
Так что я удивлен, как моя программа работала, хотя я не включил unistd.h?
Ниже приведена моя программа. Это программа для копирования содержимого исходного файла в целевой файл с помощью системных вызовов read() и write().
#include<stdio.h>
#include<fcntl.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<stdlib.h>
int main()
{
/* Declaring the buffer. */
/* Data read by read() will be stored in this buffer. */
/* Later when write() is used, write() will take the contents of this buffer and write to the file.*/
char buffer[512];
/* Decalring strings to store the source file and target file names. */
char source[128], target[128];
/* Declaring integer variables in which integer returned by open() will be stored. */
/* Note that this program will open a source file, and a target file. So, 2 integers will be needed. */
int inhandle, outhandle;
/* Declaring integer variable which will specify how much bytes to read or write.*/
int bytes;
/* Taking source filename from keyboard.*/
printf("\nSource File name: ");
scanf("%s",source);
/* Open the source file using open().*/
inhandle = open(source, O_RDONLY);
/* If there is error while opening source file.*/
if (inhandle == -1)
{
perror("Error opening source file.\n");
exit(1);
}
/* Taking target filename from keyboard.*/
printf("\nTarget File name: ");
scanf("%s",target);
/* Open the target file using open().*/
outhandle = open(target, O_CREAT | O_WRONLY, 0660);
/* If there is error while opening target file.*/
if (outhandle == -1)
{
perror("Error opening target file.\n");
close(inhandle);
exit(2);
}
/* Below code does following:
1. First reads (at most) 512 bytes from source file
2. Then copies them to buffer
3. If bytes read is greater than 0, write the content stored in buffer to target file.
*/
while((bytes = read(inhandle, buffer, 512)) > 0)
{
write(outhandle, buffer, bytes);
}
/* Close both source and target files. */
close(inhandle);
close(outhandle);
return 0;
}
Включены ли все предупреждения и выбран ли современный стандарт? '-Wall -Wextra -pedantic -std = c11' – Deduplicator
@Deduplicator, Как использовать -Wall и т. Д.? Являются ли они компиляторным переключателем, который я могу использовать с gcc? например: gcc -Wall hello.c? – sps
Да, они есть. Попробуйте их и не игнорируйте предупреждения. – Deduplicator