2013-03-22 97 views
1

我有用於ajax源文件的文件。每1秒瀏覽器發送一個Ajax請求以從該文件讀取實際數據。 另外我有寫在C上的實際數據寫入該文件的deamon。看看下面的代碼:如何用C重寫一個文件的全部內容

static void writeToFile_withLock(const char * file_path, const char * str) 
{ 
    struct flock fl = {F_WRLCK, SEEK_SET, 0,  0,  0 }; 
    int fd; 
    const char * begin = str; 
    const char * const end = begin + strlen(str); 

    fl.l_pid = getpid(); 

    if ((fd = open(file_path, O_CREAT | O_WRONLY)) == -1) { 
     perror("open"); 
     exit(1); 
    } 
    printf("Trying to get lock...\n"); 
    if (fcntl(fd, F_SETLKW, &fl) == -1) { 
     perror("fcntl"); 
     exit(1); 
    } 
    printf("got lock\n"); 

    printf("Try to write %s\n", str); 
    while (begin < end) 
    { 
     size_t remaining = end - begin; 
     ssize_t res = write(fd, begin, remaining); 
     if (res >= 0) 
     { 
      begin += res; 
      continue; // Let's send the remaining part of this message 
     } 
     if (EINTR == errno) 
     { 
      continue; // It's just a signal, try again 
     } 
     // It's a real error 
     perror("Write to file"); 
     break; 
    } 

    fl.l_type = F_UNLCK; /* set to unlock same region */ 

    if (fcntl(fd, F_SETLK, &fl) == -1) { 
     perror("fcntl"); 
     exit(1); 
    } 

    printf("Unlocked.\n"); 

    close(fd); 

} 

問題:如果以前的數據是>新數據然後舊的幾個符號保存在文件的末尾。

如何重寫全文件內容?

在此先感謝。

+0

使用'O_TRUNC'標誌打開。 – 2013-03-22 16:36:27

回答

2

O_TRUNC添加到open()調用...

O_TRUNC

如果該文件已經存在,並且是一個普通文件和開放模式 允許寫入(即是O_RDWR或O_WRONLY),它將被截斷爲長度爲 。如果文件是FIFO或終端設備文件,則忽略O_TRUNC 標誌。否則,O_TRUNC的效果未指定。

0

你基本上有兩種選擇。在打開文件時,將open的第二個參數的O_TRUNC位設置爲放棄所有內容,或者在完成時放棄ftruncate以放棄不需要的文件的內容。 (或者使用truncate,但由於您已經有一個打開的文件描述符,因此沒有優勢。)

相關問題