我有一个已经标记的文件,但是我需要将每个标记存储在一个数组中,以便以后用作参数。我该怎么做呢?
// Read in File //
FILE *fp;
char buffer[100];
fp = fopen(params, "r");
printf("Here is filename...");
printf("%sn", params);
fseek(fp, 0, SEEK_END);
//byte_size = ftell(fp);
rewind(fp);
if (fgets(buffer,sizeof(buffer),fp) != NULL)
{
char*p, *b;
b = buffer;
printf("parsing %s", buffer);
while ((p = strsep(&b, ",")) != NULL)
{
printf("param: %sn",p);
}
}
fclose(fp);
使用链表并稍后将其转换为数组可能是好的,因为我们不知道有多少令牌。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *strsep(char **stringp, const char *delim);
typedef struct node_tag {
char *str;
struct node_tag* next;
} list_node;
list_node* create_node(const char *str) {
list_node* n = malloc(sizeof(list_node));
if (n == NULL) exit(1);
if (str == NULL) {
n->str = NULL;
} else {
n->str = malloc(sizeof(char) * (strlen(str) + 1));
if (n->str == NULL) exit(1);
strcpy(n->str, str);
}
n->next = NULL;
return n;
}
int main(void) {
const char *params = "dummy";
FILE *fp;
char buffer[100];
list_node *head = NULL;
list_node **tail = &head;
unsigned int count = 0;
unsigned int i;
char **array;
fp = stdin;//fopen(params, "r");
printf("Here is filename...");
printf("%sn", params);
fseek(fp, 0, SEEK_END);
//byte_size = ftell(fp);
rewind(fp);
if (fgets(buffer,sizeof(buffer),fp) != NULL)
{
char*p, *b;
b = buffer;
printf("parsing %s", buffer);
while ((p = strsep(&b, ",")) != NULL)
{
printf("param: %sn",p);
*tail = create_node(p);
tail = &(*tail)->next;
count++;
}
}
array = malloc(sizeof(char*) * count);
if (array == NULL) return 1;
for (i = 0; i < count && head != NULL; i++) {
list_node *next = head->next;
array[i] = head->str;
// Don't free(head->str) because it is used
free(head);
head = next;
}
for (i = 0; i < count; i++) {
printf("array[%u] = %sn", i, array[i]);
}
for (i = 0; i < count; i++) free(array[i]);
free(array);
//fclose(fp);
return 0;
}
如果您知道令牌的数量,则可以简单地使用array。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *strsep(char **stringp, const char *delim);
#define ARRAY_SIZE 8
int main(void) {
const char *params = "dummy";
FILE *fp;
char buffer[100];
char *array[ARRAY_SIZE];
int array_count = 0;
int i;
fp = stdin;//fopen(params, "r");
printf("Here is filename...");
printf("%sn", params);
fseek(fp, 0, SEEK_END);
//byte_size = ftell(fp);
rewind(fp);
if (fgets(buffer,sizeof(buffer),fp) != NULL)
{
char*p, *b;
b = buffer;
printf("parsing %s", buffer);
while ((p = strsep(&b, ",")) != NULL)
{
printf("param: %sn",p);
if (array_count < ARRAY_SIZE)
{
array[array_count] = malloc(sizeof(char) * (strlen(p) + 1));
strcpy(array[array_count], p);
array_count++;
}
}
}
for (i = 0; i < array_count; i++) {
printf("array[%u] = %sn", i, array[i]);
}
for (i = 0; i < array_count; i++) free(array[i]);
//fclose(fp);
return 0;
}