【问题标题】:Storing line by line from text file into char array using char pointer使用char指针将文本文件中的逐行存储到char数组中
【发布时间】:2016-05-04 09:21:28
【问题描述】:

您好,我正在编写一个程序来执行来自文本文件的命令。下面的代码用于先将一行一行的存入char数组中。

所以我希望它做类似的事情

args[0]= The first line of text file  
args[1]= The second line of text file
... and so on

在我的代码中,所有数组都将被最后一个数组覆盖。我不知道为什么。

谁能帮我解决这个问题并告诉我为什么我的代码会这样。我还需要保留 char *args[]。因为我稍后会在 execvp() 中使用它。

int main(int argc, const char * av[]) {    
    FILE *fp;    
    fp = fopen(av[1],"r");

    int n_lines=0;        
    char in[100],*args[16];        
    int size=sizeof(in);

     while(fgets(in, size, fp)!=NULL){        
        args[n_lines] = in;                
        printf("Args[0] is %s\n",args[0]);            
        n_lines++;
    }

     printf("Now Args[0] is %s\n",args[0]);
}

输出

zacks-MacBook-Pro:prac2 zack$ ./a.out test    
Args[0] is ./addone    
Args[0] is ./add    
Now Args[0] is ./add

【问题讨论】:

  • 独立于你的问题:你知道如果你的文件超过 16 行你会遇到问题。
  • 独立于您的问题,您应该检查文件是否存在并在读取内容时关闭文件指针...

标签: c arrays pointers char system


【解决方案1】:
int n_lines=0;        
char in[100],*args[16];        
int size=sizeof(in);

while(fgets(in, size, fp)!=NULL){        
    args[n_lines] = in;                
    printf("Args[0] is %s\n",args[0]);            
    n_lines++;
}

in 的值在每次迭代时都会被覆盖,您需要预留空间(使用malloc->strcpystrdup 如果可用):

char in[100], *args[16];

while (fgets(in, sizeof in, fp) != NULL) {
    args[n_lines] = strdup(in);
    ...
    n_lines++;
}

或者使用二维数组(fgets 需要调整 sizeof):

char in[16][100];

while (fgets(in[n_lines], sizeof in[0], fp) != NULL) {
    ...
    n_lines++;
}

正如@MichaelWalz 在 cmets 中指出的那样:如果您的文件超过 16 行,您将遇到问题。

改成

while (fgets(in[n_lines], sizeof in[0], fp) != NULL) {
    ...
    if (++n_lines == (sizeof in / sizeof in[0])) break;
}

【讨论】:

  • @MichaelWalz,感谢您的编辑,我的英语很差:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-07
  • 2021-01-26
  • 2014-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多