簡體   English   中英

解析字符串(Unix Shell)

[英]Parsing a string (Unix Shell)

我已經嘗試了數千種選項來解析我存儲在緩沖區內的字符串集,但是找不到在字符串* args []中逐個字符串存儲它們的好方法。 之后,我要做的是在子進程中運行execvp。

謝謝!!

#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>


#define MAX_LINE 80

int main(){

char *args[MAX_LINE/2 + 1];
int should_run = 1;
int background = 1;
char buffer[1024];

    while (should_run){
            printf("jaime$ ");
            int i = 0;
            fflush(stdout);
            while (fgets(buffer, 1024, stdin)){
                    sscanf(buffer, "%s", args[i]);
                    i++;
            }

            pid_t pid;
            pid = fork();

            if (pid < 1){
                    fprintf(stderr, "fork() failed");
..........

代碼未分配內存以節省混亂

sscanf(buffer, "%s", args[i]);  args[i] is not initialized

而是分配所需的內存。

下面使用"%n"記錄掃描中該點在字符串中的偏移量。 " "占用領先的空白。 "%n"將掃描偏移量存儲在n1 “%* s”的掃描方式與"%s" ,但不存儲結果。 最后, "%n"將掃描偏移量存儲在n2 現在代碼知道n2-n1 ,即要提取的buffer的寬度。

 while (fgets(buffer, 1024, stdin)) {
   int n1 = 0;
   int n2 = 0;
   sscanf(buffer, " %n%*s%n", &n1, &n2);
   int length = n2 - n1;
   args[i] = malloc(length + 1);
   if (args[i] == NULL) {
     Handle_OutOfMemory(); // TBD code to cope with OOM.
   } 
   memcpy(args[i], &buffer[n1], length);
   args[i][length] = '\0';
   i++;
 }

 // use args[0] to args[i-1]

 for (int j = 0  j < i; j++) {
   free(args[j]);
   j++;
 }

使用標准的C庫解析復雜的字符串既不容易,也不干凈。 如果您要創建外殼程序(看起來就是這樣),則尤其如此。

我建議您看一下lexyacc ,它們可以用來為復雜語法(包括像bash這樣的shell語言)構建標記器和解析器。

這是有關lex和yacc的不錯的入門教程。 如果您想通過示例學習,可以查看bash / parse.y ,盡管其語法相當復雜且復雜。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM