PDA

View Full Version : Il C non perdona...nemmeno sui file!


Cimmo
06-03-2003, 00:24
Perche' non va'? La write fallisce dicendo: "Failed to write: [Err 9]: Bad file descriptor"


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

int main(int argc, char *argv[])
{
int filefd;
long cont,written,toWrite;
char *str;

printf("\n\n");

if (argc!=3)
{
printf ("2 parameters needed\n");
printf ("Usage: produceByte FILENAME SIZE\n\n");

exit(1);
}

str=(char *) malloc(sizeof(char[1000]));
filefd=open(argv[1],O_CREAT,0777);

cont=0;
written=0;
sscanf(argv[2],"%ld",&toWrite);

while (written<toWrite)
{
sprintf(str,"%ld-",cont);
int err=write(filefd,str,strlen(str));

if (err<0)
{
char msgerror[1024];
sprintf(msgerror,"Failed to write: [Err %d]",errno);
perror(msgerror);
fflush(stderr);
exit(1);
}

written+=strlen(str);
printf("Written: %ld\n",written);

cont++;
}

close(filefd);

return(0);
}

ilsensine
06-03-2003, 08:16
Hai creato il file senza indicare che ci vuoi anche scrivere. Inoltre ti consiglio di usare O_TRUNC, per azzerare un eventuale file esistente.
filefd=open(argv[1],O_RDWR|O_CREAT|O_TRUNC,0777);

Cimmo
06-03-2003, 09:12
Originally posted by "ilsensine"

Hai creato il file senza indicare che ci vuoi anche scrivere. Inoltre ti consiglio di usare O_TRUNC, per azzerare un eventuale file esistente.
filefd=open(argv[1],O_RDWR|O_CREAT|O_TRUNC,0777);
Ok pensavo che O_CREAT comprendesse anche i flag per la scrittura...grazie!