我真正想做的是:正確啟動一個二維字符陣列(字串陣列),將檔案的內容加載到陣列中,打破另一個函式中的每個'\ n'。
由于我們無法從 C 中的函式回傳雙精度陣列,因此目前我正在嘗試使用 strncpy() 逐行讀取檔案。我嘗試了很多變體,但我一直在弄亂記憶體,所以我遇到了很多段錯誤和總線錯誤。
這是一個模態,展示了我想要做的事情是多么簡單:
int main()
{
char *file_content[];
load_file_to_array(file_content);
}
void load_file_to_array(char *to_load[]){
// something to update file_content
}
編輯:我沒有要求任何人為我撰寫代碼。我對研究這個特定主題感到沮喪,所以我決定問問你們的想法。任何不同的方法或方法本身都值得贊賞。
我對我的方法有一種很好的預感,那就是它完全偏離了軌道。
我看過很多關于動態記憶體的帖子和文章。我發現最接近我想要完成的事情是這篇文章
編輯[2]:
正如@pm100 在我嘗試的評論中解釋的那樣:
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 255
void load_array(char *, char *[]);
int main(){
// NULL terminate array
char *fn = "text.txt";
char *arr[MAX_SIZE] = { NULL };
// Also tried:
// char **arr = malloc(sizeof * char*MAX_SIZE)
// arr[0] = malloc(sizeof(char)*MAX_SIZE);
load_array(fn, arr);
}
void load_array(char *fn, char *fcontent[]){
FILE * file = fopen(fn, "r");
char line[MAX_SIZE];
int i = 0;
// read file line by line with fgets()
while (fgets(line, sizeof(line), file))
{
// this part I'm not sure of. maybe setting with fgets makes more sense.
strcpy(fcontent[i], line);
i ;
// realloc()
fcontent = realloc(fcontent, sizeof (char*) * (i 1));
fcontent[i] = malloc(sizeof(char) * MAX_SIZE);
// null terminate the last line
*fcontent[i] = 0;
}
fclose(file);
}
運行程式后出現段錯誤。
uj5u.com熱心網友回復:
除了說這遠不是一個有效的解決方案之外,您還可以稍微修改一下:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_SIZE 1024
char** load_array(const char *fn) {
char** fcontent = (char**)malloc(0);
FILE * file = fopen(fn, "r");
char line[MAX_SIZE];
int i = 0;
// read file line by line with fgets()
while (fgets(line, sizeof(line), file))
{
fcontent = (char**)realloc(fcontent, (i 1) * sizeof(char*));
fcontent[i] = (char*)malloc(strlen(line) 1);
// this part I'm not sure of. maybe setting with fgets makes more sense.
strcpy(fcontent[i], line);
i ;
}
fcontent = (char**)realloc(fcontent, (i 1) * sizeof(char*));
fcontent[i] = NULL;
fclose(file);
return fcontent;
}
int main()
{
char **lines = load_array("test.txt");
int i = 0;
while (lines[i])
printf("%s", lines[i ]);
i = 0;
while (lines[i])
free(lines[i ]);
free(lines);
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/436653.html
上一篇:滾動條隱藏但一個節目
下一篇:查找檔案中的最大數字
