我想将文件的以下内容加载到数组中。 文件内容:
[1,2,3,4,5]
[2,3]
[2]
[1,4,5,6,8,9]
现在,我想将第一行加载到整数数组 'a' ( a ={1,2,3,4,5})
中并执行一些操作。免费的获取下一行并加载到 'a' (a = {2,3})
并执行一些操作等等......直到文件末尾。
注意:每行可以有不同的数字数量。(我们不知道每行的数字数量)
如何扫描每一行并仅获取数字并将它们存储在数组中?
我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define DELIM " \r\n\t!@#$%^&*()_+-={}|\\:\"'?¿/.,<>’¡º×÷‘"
int main(int argc, char *argv[]){
int lineIdx = 0;
int charIdx = 0;
int TERMINATOR = 1753775;
char *token = "tmp";
char *orLine = malloc(4096 * sizeof(char));
char **importedLine = malloc(4096 * sizeof(orLine));
int tokenizedArray[100][100];// = malloc(sizeof(orLine * numOfLines));
FILE *f = fopen(argv[1], "r");
while(fscanf(f, "%s", orLine) != EOF){
importedLine[lineIdx] = orLine;
for(charIdx = 0; charIdx < strlen(importedLine[lineIdx]); charIdx++){
importedLine[lineIdx][charIdx] = importedLine[(lineIdx)][(charIdx+1)];
}
importedLine[lineIdx][(strlen(importedLine[lineIdx])-1)] = NULL;
token = strtok(importedLine[lineIdx], ", ");
charIdx = 0;
while(token != NULL){
tokenizedArray[lineIdx][charIdx] = atoi(token);
token = strtok(NULL, ", ");
charIdx++;
}
tokenizedArray[lineIdx][(charIdx)] = TERMINATOR;
lineIdx++;
}
tokenizedArray[(lineIdx)][0] = TERMINATOR;
fclose(f);
lineIdx = 0;
charIdx = 0;
while(tokenizedArray[lineIdx][charIdx] != TERMINATOR){
while(tokenizedArray[lineIdx][charIdx] != TERMINATOR){
printf("%d ",tokenizedArray[lineIdx][charIdx]);
charIdx++;
}
lineIdx++;
charIdx = 0;
printf("\n");
}
return 0;
}
提前致谢
最佳答案
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef int Type;
typedef struct vector {
size_t size;
size_t capacity;
Type *array;
} Vector;
Vector *vec_make(void){
Vector *v = malloc(sizeof(*v));
if(v){
v->size = 0;
v->capacity=16;
v->array = malloc(v->capacity * sizeof(Type));
}
return v;
}
void vec_free(Vector *v){
free(v->array);
free(v);
}
void vec_add(Vector *v, Type value){
v->array[v->size++] = value;
if(v->size == v->capacity){
Type *temp;
temp = realloc(v->array, sizeof(Type)*(v->capacity += 16));
if(!temp){
perror("realloc at vec_add");
vec_free(v);
exit(-1);
}
v->array = temp;
}
}
int main(int argc, char *argv[]){
if(argc != 2){
fprintf(stderr, "Usage : %s filename\n", argv[0]);
exit(EXIT_FAILURE);
}
FILE *f = fopen(argv[1], "r");
if(f == NULL){
perror("fopen");
exit(EXIT_FAILURE);
}
char line[4096];
while(fgets(line, sizeof line, f)){
static const char *delimiter = "[,] \t\n";
Vector *v = vec_make();
char *number = strtok(line, delimiter);//Format don't check
for(; number; number = strtok(NULL, delimiter)){
vec_add(v, atoi(number));
}
//some operation : print out
int size = v->size;
int *a = v->array;
for(int i = 0; i < size; ++i){
if(i)
putchar(',');
printf("%d", a[i]);
}
putchar('\n');
vec_free(v);
}
fclose(f);
return 0;
}
关于c - 从c中的文件中读取多行(不同长度),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31309018/