fopen C上的分段错误

时间:2015-03-05 15:30:38

标签: c file fopen

伙计我有这个代码

#include <stdio.h>

typedef struct
{
    int numero, notaF, notaE;
    char nome[100];
} ALUNO;

void lerFicheiro(char path[], ALUNO alunos[], int *i);
void escreverFicheiro(char path[], ALUNO alunos[], int tamanho);

int main()
{
    //Declarações 
    int i=0,t=0;
    char path[999], wpath[999];
    ALUNO alunos[999];
    FILE *f;

    //Introdução do nome do ficheiro para leitura e para escrita
    printf("Introduza a localização do ficheiro para leitura: ");
    fgets(path,999,stdin); //segmentation fault e o fopen dá null (apenas no read)
    printf("Introduza a localização do ficheiro para escrita: ");
    fgets(wpath,999,stdin);

    //Leitura do ficheiro
        lerFicheiro(path,alunos,&t);

    //Escrita do ficheiro
    escreverFicheiro(wpath, alunos, t);

    return 0;
}

void lerFicheiro(char path[], ALUNO alunos[],int *i)
{
    FILE *f = fopen("dados1.txt","r");
    if(f!=NULL)
    {
        while(fscanf(f,"%d\n",&alunos[*i].numero)==1)
        {
            fgets(alunos[*i].nome,100,f);
            fscanf(f,"%d\n",&alunos[*i].notaF);
            fscanf(f,"%d\n",&alunos[*i].notaE);
            *i=*i+1;
        }
    }
    else
    {
        printf("Erro ao abrir o ficheiro\n");
    }
    fclose(f);
}

void escreverFicheiro(char path[], ALUNO alunos[], int tamanho)
{
    FILE *f = fopen(path,"w+");
    int i = 0, notaFinal = 0;
    for(i=0;i<tamanho;i++)
    {
        if(alunos[i].notaF>alunos[i].notaE)
            notaFinal = alunos[i].notaF;
        else
            notaFinal = alunos[i].notaE;
        if(notaFinal>=10)
        {
            fprintf(f,"%d\n",alunos[i].numero);
            fputs(alunos[i].nome,f);
            fprintf(f,"%d\n",notaFinal);
        }   
    }
    fclose(f);
}

但是在lerFicheiro函数上,如果我用路径替换“dados1.txt”,我将在英文“无法打开文件”中出现错误“Erro ao abrir o ficheiro”并且在分段错误之后 我无法找到错误

1 个答案:

答案 0 :(得分:2)

您应该从文件名

中删除尾随的newline
char *sptr = strchr(path, '\n');
if (sptr) *sptr = '\0';

同时移动fclose(f);,您正试图关闭未打开的文件。

void lerFicheiro(char path[], ALUNO alunos[],int *i)
{
    FILE *f = fopen("dados1.txt","r");
    if(f!=NULL)
    {
        while(fscanf(f,"%d\n",&alunos[*i].numero)==1)
        {
            fgets(alunos[*i].nome,100,f);
            fscanf(f,"%d\n",&alunos[*i].notaF);
            fscanf(f,"%d\n",&alunos[*i].notaE);
            *i=*i+1;
        }
        fclose(f);
    }
    else
    {
        printf("Erro ao abrir o ficheiro\n");
    }
}