0

我的程序必须像这样读取文件的内容:

name_of_program < Test.txt

Test.txt 是一个二维整数数组(整数由空格分隔,有时是多个整数,整数行由 EOL 分隔),但长度和高度未知。我如何确定它们?我计划将链表的节点中的每一行存储为整数数组。

编辑:我的程序大致如下所示:

#include <stdio.h>
#include <stdlib.h>

struct node {
    int *val; //stores the row
    struct node *next;
};

struct node *addnode(int *val, struct node *next);
struct node *mergesort(struct node *head, int column); //column by which I'll sort it
struct node *merge(struct node *head_one, struct node *head_two, int column);

int main(int column) //number of column to sort by, should run like that "name_of_program column < Test.txt" in Unix systems
{
    struct node *head;
    struct node *current;
    struct node *next;
    head = NULL;

    /* Reading from stdin line by line, writing it to list and linking nodes - I have only the last bit done */

    head = mergesort(head, column);

    /* Writing to stdout, row by row of sorted list, I can't do that without the previous bit */

    for(current = head; current != NULL; current = next)
        next = current->next, free(current);
    return 0;
};


struct node *addnode(int *val, struct node *next)
{
    struct node *tnode;
    tnode = (struct node*)malloc(sizeof(*tnode));
    if(tnode != NULL) {
        tnode->val = val; //not sure about this line, would it write whole array, or just one element?
        tnode->next = next;
    };
    return tnode;
}

struct node *mergesort(struct node *head, int column)
{
    struct node *head_one;
    struct node *head_two;
    if((head == NULL) || (head->next == NULL))
        return head;
    head_one = head;
    head_two = head->next;
    while((head_two != NULL) && (head_two->next != NULL)) {
        head = head->next;
        head_two = head->next->next;
    };
    head_two = head->next;
    head->next = NULL;
    return merge(mergesort(head_one, column), mergesort(head_two, column), column);
}

struct node *merge(struct node *head_one, struct node *head_two, int column)
{
    struct node *head_combined;
    if(head_one == NULL)
        return head_two;
    if(head_two == NULL)
        return head_one;
    if(head_one->val[column] < head_two->val[column]) {
        head_combined = head_one;
        head_combined->next = merge(head_one->next, head_two, column);
    } else {
        head_combined = head_two;
        head_combined->next = merge(head_one, head_two->next, column);
    };
    return head_combined;
}
4

1 回答 1

0

您可以从在 C 中逐行读取文件开始,您可以使用 getline 函数。考虑到行的最大长度,您将需要分配足够大的缓冲区。处理行,从行中检索整数,这可以通过循环行缓冲区和跳过空格来完成。整数可以存储在您可以创建的二维数组或链表中。

于 2013-06-04T10:02:32.143 回答