c - 使用字符指针将文本文件逐行存储到字符数组中

标签 c arrays pointers char system

您好,我正在编写一个程序来执行文本文件中的命令。下面的代码用于先逐行存入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

最佳答案

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->strcpy or strdup if available) :

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 在评论中指出的那样:如果您的文件超过 16 行,您就会遇到问题。

更改为

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

关于c - 使用字符指针将文本文件逐行存储到字符数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37023515/

相关文章:

c - 在 GNU C 中列出时跳过目录

javascript - Angular 4函数仅从第二次开始起作用

java - 对字符串中的字符求和并打印最大的字符串(java)

c - Atmega168 I2C 作为主机

c++ - 在 Xcode 4 中包含 C/C++ header

c - 如何使结构数组成为单个字符串

c++ - 指针只保存指向其他变量的地址吗?

c - 如何使用通用 void 指针将值扫描到数组中?

c - 为什么我们使用指向指针的指针

c - 将文件读入结构体