【问题标题】:Read till EOF but exec every line upto the \n读到 EOF 但执行每一行直到 \n
【发布时间】:2012-06-28 07:47:57
【问题描述】:

仅使用系统调用,您如何将文件读取到 EOF 并在此过程中执行程序中的每一行,直到行尾。 我文件中的每一行都有一个必须执行的程序名称。

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

 }

【问题讨论】:

    标签: c system-calls


    【解决方案1】:

    我最近创建了一个具有类似功能的程序:

    #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));
        }
    }
    

    【讨论】:

    • 当你到达行尾时你会做什么?我不明白。
    • 我使用strdup创建了一个新的行实例,然后用系统执行它,最后我将行的索引设置为0
    【解决方案2】:

    试试这样的:

    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 必须进行边界检查和/或动态内存分配以避免缓冲区溢出。

    【讨论】:

    • 不想使用..fgetline 或 fopen。只是系统调用。
    • like.. 对于 fopen,我只想使用 open。对于 fgetline,我只想使用..read()。基本上,来自 linux 的 man 2 page。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-23
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 2010-09-06
    相关资源
    最近更新 更多