我的#include <unistd.h>
源文件中包含了手册页中指定的标题sync(2)
。但是,当我编译我的程序时,我收到以下警告。
./test.c:25:3: 警告:函数'sync'的隐式声明</p>
我在这里错过了什么吗?下面是我的小测试程序的源代码。
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
int main(int argc, char *argv[]) {
// Open file ./test.txt and append to it
int fd = open("./test.txt", O_RDWR | O_CREAT | O_TRUNC, 0);
if (fd < 0) {
perror("Failure to open file: ");
close(fd);
return(1);
}
// Write Hello World\n\0 100 time to ./test.txt
for (int i = 0; i < 100; ++i) {
ssize_t bytes = write(fd, "Hello World\n", 12); // 12 for Null '\0'
if (bytes != 12) {
perror("Failure to write to file");
close(fd);
return(1);
}
}
// Close the file for the exercise
sync();
close(fd);
// This will allow lseek to go back
fd = open("./test.txt", O_RDWR, 0);
// This will not allow lseek to go back
//fd = open("./test.txt", O_RDWR | O_APPEND, 0);
if (fd < 0) {
perror("Failure to open files: ");
close(fd);
return(1);
}
if (lseek(fd, -500, SEEK_END) == -1) {
perror("Test failed: ");
close(fd);
return(1);
}
ssize_t bytes = write(fd, "\n\nHello Dog\n\n", 14);
if(bytes != 14) {
perror("Failure to write: ");
close(fd);
return(1);
}
write(1, "Done!!!\n", 9);
close(fd);
return(0);
}