2012-11-08 41 views
-4

我寫了下面的代碼:用c語言編寫的Linux系統調用write()不起作用?

它應該接受一個文件名並創建並寫入它。什麼都沒發生。 我不明白爲什麼。我試着搜索,看到類似的例子應該工作正常。 如果有問題,我正在使用VirtualBox和Xubuntu。

#include <stdio.h> 
#include <stdlib.h> 
#include <dirent.h> 
#include <sys/stat.h> 
#include <sys/types.h> 
#include <fcntl.h> 
#include <time.h> 
#include <assert.h> 
#include <errno.h> 
#include <string.h> 

#define SIZE_4KB  4096 
#define FILE_SIZE  16777216 



/*Generate a random string*/ 
char* randomStr(int length) 
{ 
     int i = -1; 
     char *result; 
     result = (char *)malloc(length); 
     while(i++ < length) 
     { 
       *(result+i) = (random() % 23) + 67; 
       if(i%SIZE_4KB) 
         *(result+i) = '\0'; 
     } 
     return result; 
} 

void writeFile(int fd, char* data, int len, int rate) 
{ 
     int i = 0; 
     len--; 
     printf("Writing...\n"); 
     printf("to file %d :", fd); 
     while(i < len) 
     { 
       write(fd, data, rate); 
       i += rate; 
     } 
} 

int main(int argc, char** argv) 
{ 
     int i = -1, fd; 
     char *rndStr; 
     char *filePath;  
     assert (argc == 2); 
     filePath = argv[1]; 
     rndStr = randomStr(FILE_SIZE); 
     printf("The file %s was not found\n", filePath); 
     fd = open(filePath, O_CREAT, O_WRONLY); 
     writeFile(fd, rndStr, FILE_SIZE, SIZE_4KB); 
     return 0; 
} 
+0

你預計會發生什麼? – m0skit0

+2

我希望你明白'if(i%SIZE_4KB)'表示'if(i%SIZE_4KB!= 0)',即'if(i' *是* SIZE_4KB的倍數)'。 (目前,你正在將絕大多數'rndStr'設置爲空字節。) – ruakh

+0

謝謝,這種錯誤 – zehelvion

回答

3

open呼叫是錯誤的。通過將參數與OR組合來指定多個標誌。而且,當你創建一個文件時,第三個參數應該是你希望文件擁有的權限。所以,你的電話open應該是這樣的:

fd = open(filePath, O_CREAT | O_WRONLY, 0666); 
if (fd < 0) 
    Handle error… 

您應該始終從系統調用和庫函數測試的返回值,看看是否出現了錯誤。

+0

什麼是0666?它看起來不像一個字符串或數字。謝謝你的偉大答案。我沒有看到我之前嘗試過的示例中解釋的權限。 – zehelvion

+0

@ArthurWulfWhite:以'0'開始的整數文字被解釋爲八進制(base-8)常量;例如'0666'就是6×8²+ 6×8 + 6。 (除了文件權限之外,八進制不常用,除了文件權限以八進制友好的方式設計:三位用於所有者的讀/寫/執行權限,三位用於組所有者,三位用於所有其他用戶。) – ruakh

+0

這就是我的想法,所以它期望一個八進制因爲每個用戶類型有3位,讀寫和執行?有意義 – zehelvion