POSIX - problems writing to file using open and write

1

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

follow 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;
}
    
asked by anonymous 07.11.2017 / 18:26

0 answers