![](/img/trans.png)
[英]Read From File and Store Strings into a Multidimensional Array of Strings in C
[英]Read from file to array of strings, C
我正在嘗試編寫一個 function ,它使用 fgets() 將文件中的字符串讀取到字符串數組中,但我不斷收到zsh: segmentation fault
。
這是我的代碼:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void read(FILE*, char[][31],int*,int);
void printAll(char[][31],int*);
int main(int argc, char** argv) {
FILE *in = fopen("strings.dat", "r");
char strarr[50][31];
int items=0;
read(in,strarr,&items,31);
printAll(strarr,&items);
}
void read(FILE *in,char arr[][31],int *items,int len){
int i = 0;
char temp[31];
while (fgets(temp, len, in) != NULL) {
strcpy(arr[i], temp);
i++;
items++;
}
}
void printAll(char arr[][31],int *items){
for(int i = 0;i<*items;i++){
printf("String %d: %s\n",i+1,arr[i]);
}
}
我該如何解決?
您的代碼幾乎是正確的。
錯誤:
在read
function items++
是錯誤的,這會增加指針但您想增加指針指向的變量,因此您需要(*items)++
代替。
根據平台read
將與 posix read
function 沖突。
該程序將在以下情況下失敗:
如果文件strings.dat
不存在in
NULL
並對 NULL FILE
指針執行文件操作會導致未定義的行為,這通常表現為段錯誤。 這可能就是發生在你身上的事情。
如果文件包含超過 50 行,您將溢出strarr
這也會導致未定義的行為
如果文件中的行超過 31 個字符,行將被截斷和/或拆分。
獎金:
temp 變量不是必需的,您可以直接讀入數組:
而不是這個:
char temp[31];
while (fgets(temp, len, in) != NULL) {
strcpy(arr[i], temp);
...
你可以有這個:
while (fgets(arr[i], len, in) != NULL) {
...
帶有更正的最終代碼:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void read(FILE*, char[][31], int*, int);
void printAll(char[][31], int*);
int main(int argc, char** argv) {
FILE* in = fopen("strings.dat", "r");
if (in == NULL)
{
printf("file does not exist\n");
exit(1);
}
char strarr[50][31];
int items = 0;
read(in, strarr, &items, 31);
printAll(strarr, &items);
}
void read(FILE* in, char arr[][31], int* items, int len) {
int i = 0;
while (fgets(arr[i], len, in) != NULL) {
i++;
(*items)++;
}
}
void printAll(char arr[][31], int* items) {
for (int i = 0; i < *items; i++) {
printf("String %d: %s\n", i + 1, arr[i]);
}
}
read
的替代版本
void read(FILE* in, char arr[][31], int* items, int len) {
int i = 0;
while (fgets(arr[i++], len, in) != NULL) {
(*items)++;
}
}
更短:
void read(FILE* in, char arr[][31], int* items, int len) {
for (int i = 0; fgets(arr[i], len, in) != NULL; i++)
(*items)++;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.