POSIX - problems to write to file using open and write

Asked

Viewed 90 times

1

About this code below, is giving write problem, but if I use creat without flags it runs. The goal is to copy a file, the file that will be copied is called 'test.txt' and what will be created 'novoteste.txt', but if the new.txt is already created is to return an error message. With creat you can’t do it without gambiarra (as far as I know). That’s why I’m trying to use the open.

follows the code:

#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>

int main(void) {

  /*-------criando o novo arquivo---------*/
  mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
  /*
  S_IRUSR
      read permission, owner
  S_IWUSR
      write permission, owner
  S_IRGRP
      read permission, group
  S_IROTH
      read permission, others
  */
  struct stat     statbuf;
  int arqEntrada, arqSaida, tamanho, tambloco;
  char *filename = "teste.txt";

  if( ( arqEntrada = open(filename, O_RDONLY | O_NONBLOCK, mode) ) == -1) {
    printf("Erro ao abrir arquivo!\n");
    exit(1);
  }
  if ( stat(filename, &statbuf) == -1) {
    printf("Erro no stat!");
    exit(1);
  }
  tamanho = statbuf.st_size;
  tambloco = statbuf.st_blksize;

  char *filename2 = "novoteste.txt";

  if( ( arqSaida = open(filename2, O_CREAT | O_EXCL, mode) ) == -1)  {
    printf("Erro ao criar novo arquivo!\n");
    exit(1);
  }

  ssize_t bytes_read, bytes_written;
  char buf[tamanho];
  size_t nbytes;

  nbytes = sizeof(buf);

  if( ( bytes_read = read(arqEntrada, buf, nbytes) ) == -1) {
    printf("Erro no read!\n");
    exit(1);
  }

  if( ( bytes_written = write(arqSaida, buf, nbytes) ) == -1) {
    printf("Erro no write!\n");
    exit(1);
  }
return 0;
}
  • //these are the libraries and sorry for the bad formatting, I can no longer edit. n #include <sys/stat. h> #include <sys/types. h> #include <fcntl. h> #include <stdlib. h> #include <stdio. h> #include <unistd. h> #include <string. h>

1 answer

0

At the time of creating the copy file, you need to inform Read and Write permission in this new copy file with the flag O_RDWR:

if( ( arqSaida = open(filename2, O_CREAT | O_EXCL | O_RDWR, mode) ) == -1)  {
  printf("Erro ao criar novo arquivo!\n");
    exit(1);
}

This way, the new file is created (O_CREAT and O_EXCL) and is allowed to write the contents of the original file (O_RDWR).

References on the oflags and modes can be seen in this codewiki

Browser other questions tagged

You are not signed in. Login or sign up in order to post.