[英]Need help scanning the contents of a file into an array of pointers
I need to read in a file, each line of the file has one string on it (max 50 char long) and i need to store each line into an array of pointers. 我需要读取一个文件,文件的每一行上都有一个字符串(最大50个字符长),我需要将每一行存储到一个指针数组中。 So if the file reads:
因此,如果文件显示为:
1234
abcd
5667
...
Then the array (called functions) would be *functions[0] = 1234, *functions[1]= abcd and so on... 然后数组(称为函数)将是* functions [0] = 1234,* functions [1] = abcd,依此类推...
I've tried a few things now and i can't quite seem to get it to work. 我现在已经尝试了几件事,但似乎还不太能正常工作。 This is the start of my code, or at least the parts pertaining to my confusion:
这是我的代码的开始,或者至少是与我的困惑有关的部分:
#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");
I've tried a few things but I can't manage to make *functions store the values properly. 我已经尝试了一些方法,但是我无法使* function正确存储值。 Can someone help me out?
有人可以帮我吗? :)
:)
#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]);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.