strchr()
can help:
while (fgets(str, sizeof str, fp)) {
char *arr[2], *ptr;
arr[0] = str;
if ((ptr = strchr(str, ','))) {
arr[1] = ptr + 1;
*ptr = '\0';
} else {
exit(EXIT_FAILURE);
}
printf("<%s> <%s>\n", arr[0], arr[1]);
}
Notice that you may need to strip the trailing newline lefted by fgets()
or ommit the \n
in printf
If you need to store those strings in fresh memory, then there is a bit more of work, you can realloc()
or use a linked list (always prefer linked lists when you don't know the number of lines before-hand):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node {
void *data;
struct node *next;
};
/* Returns a pointer to an allocated string */
extern char *strdup(const char *);
/* Insert a node and returns a pointer to the data */
static void *enqueue(struct node **root, void *data)
{
struct node *node;
if (root == NULL) {
return NULL;
}
node = malloc(sizeof *node);
if (node == NULL) {
return NULL;
}
if (*root == NULL) {
node->next = node;
} else {
node->next = (*root)->next;
(*root)->next = node;
}
node->data = data;
*root = node;
return data;
}
/* Delete a node and returns a pointer to the data */
static void *dequeue(struct node **root)
{
struct node *node;
void *data = NULL;
if (root == NULL) {
return NULL;
}
node = *root;
if (node != NULL) {
node = node->next;
data = node->data;
if (*root == node) {
*root = NULL;
} else {
(*root)->next = node->next;
}
free(node);
}
return data;
}
int main(void)
{
struct node *head = NULL;
char str[256];
char **arr;
char *ptr;
/* While we don't hit EOF */
while (fgets(str, sizeof str, stdin)) {
/* Reserve space for 2 pointers */
arr = malloc(sizeof(*arr) * 2);
if (arr == NULL) {
perror("malloc");
exit(EXIT_FAILURE);
}
/* If we find a comma */
if ((ptr = strchr(str, ','))) {
/* Store the second string */
arr[1] = strdup(ptr + 1);
if (arr[1] == NULL) {
perror("strdup");
exit(EXIT_FAILURE);
}
/* Strip the string */
*ptr = '\0';
/* If we don't find a comma */
} else {
exit(EXIT_FAILURE);
}
/* Store the first string */
arr[0] = strdup(str);
if (arr[0] == NULL) {
perror("strdup");
exit(EXIT_FAILURE);
}
/* Add a node to the queue*/
if (enqueue(&head, arr) == NULL) {
perror("enqueue");
exit(EXIT_FAILURE);
}
}
/* While nodes in queue show the data and free */
while ((arr = dequeue(&head))) {
printf("%s %s", arr[0], arr[1]);
free(arr[0]);
free(arr[1]);
free(arr);
}
return 0;
}