我需要读入一个文件,文件的每一行都有一个字符串(最多 50 个字符长),并且我需要将每一行存储到一个指针数组中。因此,如果文件内容为:
1234
abcd
5667
...
那么数组(称为函数)将是 *functions[0] = 1234,*functions[1]= abcd 等等...
我现在已经尝试了一些东西,但似乎无法让它发挥作用。这是我的代码的开始,或者至少是与我的困惑有关的部分:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 201 /* 200 is th emax number of lines in the file*/
#define MAX_FUNCTION_LENGTH 51 /* each line is at ax 50 characters long
main() {
char func[MAX_FUNCTION_LENGTH]
char * functions[MAX_SIZE] /* this is my ragged array*/
FILE * inf;
inf =fopen("list.txt", "r");
我尝试了一些方法,但无法使 *functions 正确存储值。有人可以帮我吗? :)
最佳答案
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 201
int main( int argc, char **argv ) {
FILE *fp = fopen ( "D:\\personal\\input.txt","r");
if ( !fp )
exit ( -1 );
char line [50];
char *functions[MAX_SIZE];
int index = 0;
while (!feof(fp)) {
fgets (line , 50 , fp);
functions[index++] = strdup (line);
}
fclose ( fp );
for ( int i = 0; i < index; i++) {
printf ( "[%d] -> [%s]\n", i, functions[i]);
}
for ( int i = 0; i < index; i++) {
free ( functions[i]);
}
}
关于c - 需要帮助将文件内容扫描到指针数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6014194/