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>
– Renato Zembrani