错误!空列表

时间:2018-05-26 19:11:54

标签: c linked-list

我有一个问题,我的代码只在第一次执行选项3,如果我回到菜单并再试一次显示nulla。案例3是按字母顺序和反向顺序列出名称列表(InsertOrd 0 / InsertDec 1);

以下是代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <locale.h>
#define N 10000
typedef struct Lista {
    char *data;
    struct Lista *next;
} Lista;

//Ordem Crescente
struct Lista *InsertOrd(struct Lista *head, const char *data) {
    struct Lista *newp;
    struct Lista *tmp;
    char *new_data;

    /* aloca o novo item */
    newp = ((struct Lista*)malloc(sizeof(struct Lista)));
    new_data = strdup(data);
    //strdup aloca memória na pilha.
    if (newp == NULL || new_data == NULL) {
        fprintf(stderr, "out of memory");
        return NULL;
    }
    newp->data = new_data;
    newp->next = NULL;

    /* check if element should be inserted at the head */
    if (head == NULL || strcmp(new_data, head->data) < 0) {
        newp->next = head;
        head = newp;
    } else {
        /* otherwise find the point of insertion */
        tmp = head;
        while (tmp->next && strcmp(new_data, tmp->next->data) >= 0) {
            tmp = tmp->next;
        }
        newp->next = tmp->next;
        tmp->next = newp;
    }
    return head;
}

//Ordem decrescente 
struct Lista *InsertDec(struct Lista *head, const char *data) {
    struct Lista *newp;
    struct Lista *tmp;
    char *new_data;

    /* aloca o novo item */
    newp = ((struct Lista*)malloc(sizeof(struct Lista)));
    new_data = strdup(data);
    //strdup aloca memória na pilha.
    if (newp == NULL || new_data == NULL) {
        fprintf(stderr, "out of memory");
        return NULL;
    }
    newp->data = new_data;
    newp->next = NULL;

    /* verificar  o elemento deve ser inserido na cabeça*/
    if (head == NULL || strcmp(new_data, head->data) < 0) {
        newp->next = head;
        head = newp;
    } else {
        /* caso contrário, encontre o ponto de inserção */
        tmp = head;
        while (tmp->next && strcmp(new_data, tmp->next->data) <= 0) {
            tmp = tmp->next;
        }
        newp->next = tmp->next;
        tmp->next = newp;
    }
    return head;
}

void liberar(struct Lista *filmes)
{
     while (filmes != NULL) {
        struct Lista *next = filmes->next;
        free(filmes->data);
        free(filmes);
        filmes = next;
    }
}
void escrever(struct Lista * film,struct Lista * filmes)
{

    for (film = filmes; film != NULL; film = film->next) {
        printf("\n Nome: %s", film->data);
    }
}
int main()
{
    struct Lista *filmes;
    struct Lista *film;
    FILE *arq;
    char linha[600];
    int opcao;
      /* insert the items */
    filmes = NULL;
    /* open the file */
    arq = fopen("asd.txt", "r");
    if (arq == NULL) {
        printf("Ocorreu um erro!");
        return 1;
    }

do{
    printf("\n1- Listar todos os atores da lista em ordem alfabetica e alfabetica reversa");
    printf("\n2- Listar todos os filmes de um determinado ator em ordem cronologica.");
    //\n Os filmes que não tiverem a informação de ano são mostrados em último lugar
    printf("\n3- Listar todos os filmes em ordem alfabetica e alfabetica reversa");
    printf("\n4- Inserir novo filme");
    printf("\n5- Remocao de filmes");
    printf("\n6-SAIR DO PROGRAMA");
    printf("\n");
    scanf("%d",&opcao);
    if(opcao<1 || opcao>6){
        printf("\nO numero que voce digitou eh invalido!\n Por favor tente novamente.\n");
    }
    switch(opcao)
    {
        case 1: 


        break;
        case 2: 
        break;



        case 3: 


        printf("\n Voce gostaria de listar em ordem alfabetica ou alfabetica reversa (0/1) :");
        int op;

                scanf("%d",&op);
                if(op!=0 && op!=1)
                {
                    printf("\n Voce precisa digita o numero 1 ou 0 apenas!\n");
                }



        switch(op){
            case 0:
                 while (fgets(linha, sizeof linha, arq)) {
                 char *p = strtok(linha, ",");
                 filmes = InsertOrd(filmes, p);
                  }

              fclose(arq);
              escrever(film,filmes);
              liberar(filmes);

                break;
                case 1:
                while (fgets(linha, sizeof linha, arq)) {
                 char *p1 = strtok(linha, ",");
                 filmes = InsertDec(filmes, p1);
                  }

              fclose(arq);
              escrever(film,filmes);
              liberar(filmes);

                    break;
        }


        break;
        case 4: 
        break;
        case 5: 
        break;
        case 6: 
        printf("\nSaindo do programa...");
        break;
    }
}while(opcao!=6);









   // escrever(film,filmes);


    /* free the list */
    while (filmes != NULL) {
        struct Lista *next = filmes->next;
        free(filmes->data);
        free(filmes);
        filmes = next;
    }
    return 0;
}

我第一次运行case 3的选项1或0时,但是会显示:

enter image description here

1 个答案:

答案 0 :(得分:1)

你只有一个

arq = fopen("asd.txt", "r");

你有几个

fclose(arq);

选项3(两种情况)都

while (fgets(linha, sizeof linha, arq))
// ...
fclose(arq);

因此,下次使用选项3时,它会失败。

我建议在这些选项中使用fclose而不是rewind,然后在阅读之前添加<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.example</groupId> <artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <name>demo</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.2.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> <scope>compile</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <scope>compile</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>

请在构建代码时逐步测试代码。