2014-04-15 17 views
12

Cerco di aprire un file come questo in linux. Sovrascriverà uno esistente se esce. Questo è quello che voglio.Come aprire un file che sovrascrive il contenuto esistente

fout = open(out_file_name, O_WRONLY | O_CREAT, 644); 

Tuttavia, se l'attuale è 1024 byte, quando apro al precedente modo e scrivere 800 nuovi byte. Vedo ancora i 224 byte alla fine del contenuto precedente.

Come posso fare solo avere gli 800 byte che sono stati scritti?

+3

Stai cercando il flag 'O_TRUNC' su' open() '. –

+0

Probabilmente non vuoi la modalità 644. Forse vuoi la modalità 0644. Ma vedi il commento di Ciro sui nomi simbolici S_xxUSR e così via sotto. –

risposta

9

si desidera utilizzare il flag O_TRUNC a open(), da O-ing con le bandiere esistenti si dispone sopra:

int fout = open(out_file_name, O_WRONLY | O_CREAT | O_TRUNC, 644); 

Questa troncherà il file. Di seguito sono riportate le informazioni nella pagina man per open (2).

O_TRUNC 
      If the file already exists and is a regular file and the open 
      mode allows writing (i.e., is O_RDWR or O_WRONLY) it will be 
      truncated to length 0. If the file is a FIFO or terminal device 
      file, the O_TRUNC flag is ignored. Otherwise the effect of 
      O_TRUNC is unspecified. 
+1

Usa 'S_IRUSR | S_IWUSR', ecc. Da 'man 2 chmod' invece di' 644' ;-) –

Problemi correlati