如何使用标题fcntl.h和unistd.h读取和写入

How can I read and write from files using the headers fcntl.h and unistd.h?

本文关键字:读取 unistd 何使用 fcntl 标题      更新时间:2023-10-16

我正在尝试学习如何使用标头文件<fcntl.h><unistd.h>。我创建了一个小例子来测试其程序的工作,但是它没有按预期工作。这是我的代码:

#include <fcntl.h>
#include <unistd.h>
int main() {
  int in=open( "test.in", O_RDONLY, S_IREAD );
  int *a=new int[ 10 ];
  read( in, a, 10 );
  int out=open( "test.out", O_WRONLY, S_IWRITE );
  write( out, a, 10 );
  close( in ); close( out );
  return 0;
}

输入文件是:1 2 3 4 5 6 7 8 9 10

该程序正常编译,但没有创建任何输出文件。谁能告诉我我的代码怎么了?预先感谢。

分割et impera。

写作部分:

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
int main() {
  int const a[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
  int const out { open( "testnums.out", 
          O_WRONLY | O_CREAT, S_IWRITE | S_IREAD) };
  if(out==-1) {
    perror("Cannot open file");
    return 1;
  }
  ssize_t const written { write( out, a, sizeof(a) ) };
  if(written<0) {
    perror("Write error");
  }
  close( out );
  return 0;
}

编译和执行时:

$ g++ -std=c++0x -Wall -Wextra tout.cc
$ ./a.out

它写出" A"数组:

$ hexdump testnums.out 
0000000 0001 0000 0002 0000 0003 0000 0004 0000
0000010 0005 0000 0006 0000 0007 0000 0008 0000
0000020 0009 0000 000a 0000                    
0000028

请注意,这不是便携式的 - 每个编译器/架构可能在此处具有不同的输出。

这是再次阅读此内容并将其写入Stdout的部分:

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
int main() {
  int const in { open( "testnums.out", O_RDONLY ) };
  if(in==-1) {
    perror("Cannot open file");
    return 1;
  }
  int a[10];
  ssize_t const r { read( in, a, sizeof(a) ) };
  if(r!=sizeof(a)) {
    fprintf(stderr, "Could not read complete array.");
    return 1;
  }
  if(r<0) {
     perror("Read error");
     close(in);
     return 1;
  }
  close(in);
  for(unsigned int i(0); i<sizeof(a)/sizeof(int); ++i) {
    printf("%d ", a[i]);
  }
  printf("n");
  return 0;
 }

编译和执行:

$ g++ -std=c++0x -Wall -Wextra tin.cc
$ ./a.out
1 2 3 4 5 6 7 8 9 10 

常规:在您的代码中,有很多小问题(例如:检查返回值完全丢失,并非所有需要的标头文件,编写错误的字节数,...)您可能需要阅读不同的男人页面,例如

$ man 2 open
$ man 2 read
$ man 2 write
$ man 2 close

您用于打开第二个文件的标志, O_WRONLY不会创建输出文件是不存在的,您可能想尝试其他标志,例如 O_CREATEO_APPEND。此链接对您来说应该很有用,因为您可能想在其中编写时使用几个标志来处理文件创建和行为!祝你好运=)

来自OpenGroup

#include <fcntl.h>
...
int fd;
mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
char *filename = "/tmp/file";
...
fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, mode);
...

只需与您的代码进行比较。