C:将文件复制到数组中

标签 c arrays pointers buffer allocation

我基本上是在尝试自己编写sort 程序,以熟悉 C 语言。由于我正在从一个文件中读取内容,因此我考虑通过将所述文件的内容复制到一个先数组。我需要使用 mallocrealloc 来做到这一点。到目前为止,我有这个: (r 是我稍后会使用的一个选项,但我已经尝试从一开始就集成它)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define BUFFER 1024

int main (int argc, char **argv) {

    FILE *f;
    int ram = 0;
    char **save;
    int lines=0;
    char buff[BUFFER];
    size_t size;    

    int o;
    while ((o = getopt(argc, argv, "r")) != -1) {
        switch (o) {
        case 'r': ram++; break;
        case '?': fprintf(stderr, "Invalid arguments\n"); exit(0);
        default: printf("Can I even go in here?\n"); break;
        }
    }
    /* argv buildup:
    argc == 3:  
    0 - prog name
    1 - opt?
    2 - filename
    3 - NULL
    */
    if (argc > (1 + ram)) {
        f = fopen(argv[1 + ram], "r");
        if (f == NULL) {
            fprintf(stderr, "File does not exist\n");
            exit(0);        
        }

        fgets(buff, BUFFER, f);
        if (buff != NULL) {
            save = malloc(strlen(buff) + 1);            
            size = strlen(buff) + 1;
          /* here's the first segmentation fault */
            strcpy(save[lines], buff);
            lines++;    
        } else {
            fprintf(stderr, "Either reached end of file or something bad happened\n");  
        }

        while ((fgets(buff, BUFFER, f)) != NULL) {
            save = realloc(save, size + strlen(buff) + 1);
            size = size + strlen(buff) + 1;
            strcpy(save[lines], buff);
            lines++;
        }       

    } else {
        fprintf(stderr, "Please start up the program correctly\n"); 
    }

}

正如您从代码中间的注释中看到的那样,我当时遇到了段错误,而且老实说我真的不确定为什么会发生这种情况。应该有足够的可用内存。我是否错误地定位了该指针?如果是这样,我应该如何更改它才能使其正常工作?

最佳答案

    if (buff != NULL) {
        save = malloc(strlen(buff) + 1);            
        size = strlen(buff) + 1;
      /* here's the first segmentation fault */
        strcpy(save[lines], buff);
        lines++;    
    } else {

您为保存分配了错误的空间量,并且没有为字符串分配空间。你想要:

save = malloc (sizeof (char *));
*save = malloc (strlen (buff) + 1);

这会为一个字符串分配空间,并为该字符串的内容分配空间。要添加其他字符串,您需要:

save = realloc (save, (lines + 1) * sizeof (char *));
saves[lines] = malloc (strlen (buff) + 1 );
strcpy (saves[lines}, buff);
lines++;

这会为另外一个字符串分配空间,并为该附加字符串的内容分配空间。

关于C:将文件复制到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33377715/

相关文章:

c - 为什么浮点变量的地址及其指针不会产生相同的结果?

c - strtok 不只在指定的分隔符上标记

php - 如何使用混合数组和字符串更新数据库字段

java - 使用选择排序对接近排序的数组进行排序?

javascript - 在 Javascript 中显示来自数据库的图像链接 javascript 数组的 3 个随机图像

c - malloc 操作清除其他分配的内存

c - 在 C 数组中进行按位运算的最有效方法是什么

c - Uft示例编译

c - 'sizeof' 对不完整类型 'struct array[]' 的无效应用

arrays - 访问(传统)记录的字段