2012-01-21 51 views
0

只使用系統調用,您如何讀取一個文件到EOF,並在此過程中執行程序中的每一行,直到行尾。 我的文件中的每一行都將有一個必須執行的程序名稱。直到EOF,但執行每行到 n

size_t fd1 = open("inputfile.txt", O_RDWR); 
char buf1[BUFFSIZE]; 
while(read(fd1,buf1,10) != EOF) 
{ 
     if(fd1[MAXDATA] == "\n") 

} 
+0

這裏添加代碼。 – shift66

+0

這就是我去過的地方。 – madCode

回答

0

我創建了一個程序具有類似功能的近期:

#include <stdio.h> 
#include <fcntl.h> 
#include <stdlib.h> 
#include <string.h> 
#define BUFFERSIZE 1024 
#define LINEMAXSIZE 2000 
void main(int argvc,char** argv) 
{ 
int filedesc=open(argv[1],O_RDONLY); 
char buffer[BUFFERSIZE]; 

char expression[LINEMAXSIZE]; //the line 
int exprindex=0;  //line index 

int count=read(filedesc,buffer,sizeof(buffer));//read bytes 

while(count!=EOF) 
     { 
      int i=0; 
      while(i<count) 
      { 
      char c=buffer[i]; 
      if(c=='\n') 
      { 
       expression[exprindex++]='\0'; 
       char* line=strdup(expression);//create a new instance of the string 
       system(line); //execute the line 
       exprindex=0;//set line index to 0 
      } 
      else 
      { 
        expression[exprindex++]=c; 

       if(exprindex>=LINEMAXSIZE) 
       { 
       printf("Line Max length reached\n"); 
       } 

      } 

     i++; 
     } 


     count=read(filedesc,buffer,sizeof(buffer)); 
    } 
} 
+0

當你到達行尾時,你會做什麼?我沒有明白。 – madCode

+0

我使用strdup創建了一個新的實例,比用系統執行它,最後我設置了行的索引爲0 –

0

嘗試這樣:

FILE *f = fopen("filename", "r"); 
char *line = NULL; 
size_t length = 0; 
char buf[1024]; 
do 
{ 
    line = fgetline(f, &length); 
    if (line) 
    { 
     strncpy(buf, line, length); 
     buf[length] = '\0'; 
     system(buf); 
    } 
} while (line); 
fclose(f); 

另外請注意:

  1. 在生產代碼

    ,錯誤檢查是必要的,因爲fgetline()誤差之間沒有區別和EOF,並在兩種情況下都返回NULL。

  2. 從文件讀出命令並執行它們是有潛在危險的。可以插入惡意代碼並執行它。

  3. 爲了簡單起見,我使用了1024字節的緩衝區,但是爲了避免緩衝區溢出,IRL您必須執行綁定檢查和/或動態內存分配。

+0

不想使用..fgetline或fopen。只是系統調用。 – madCode

+0

什麼樣的「系統調用」?你在組裝中工作? – 2012-01-21 10:29:01

+0

like .. for fopen,我只想用open。對於fgetline,我只想使用..read()。基本上,從man 2頁的Linux。 – madCode