Nilton Schumacher F
Nilton Schumacher F

Reputation: 1168

Reading and Writing in the same FILE in C

I created a file in with the user types the name of the file he wants to create and the message inside it, but I would need that after this interaction, it would output what the user typed. I used w+ to do it since it reads and writes, but for some reason, I don't get anything from the file.

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

#define MAX 100

int main()
{
char nome_arquivo[MAX];
char mensagem[MAX];
char frase[MAX];

printf("Digite o nome do arquivo: ");
fgets(nome_arquivo, MAX, stdin);

//Remover o \n do final do fgets para que nao aja um quadradro no fim do nome do arquivo
strtok(nome_arquivo, "\n");

FILE *arq = fopen(strcat(nome_arquivo, ".txt"), "r+");

//Frase que vai dentro do arquivo
printf("Digite bastante coisa: ");
fgets(mensagem, MAX, stdin);

fprintf(arq, "%s", mensagem);

//Ler o que foi digitado e contar as ocorrencia de 'A', 'C', 'G' e 'T'
if (arq == NULL)
{
    printf("ERRO");
    system("Pause");
    exit(1);
}
else
{
    printf("\nMensagem dentro do arquivo:\n");
    fscanf(arq, "%s", frase);
    printf("%s\nS",frase);
}
fclose(arq);

}

Upvotes: 1

Views: 185

Answers (1)

Barmar
Barmar

Reputation: 780673

You need to seek back to the beginning of the file to read what you just wrote.

You should check whether arq == NULL before you try to write to it.

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

#define MAX 100

int main()
{
    char nome_arquivo[MAX];
    char mensagem[MAX];
    char frase[MAX];

    printf("Digite o nome do arquivo: ");
    fgets(nome_arquivo, MAX, stdin);

//Remover o \n do final do fgets para que nao aja um quadradro no fim do nome do arquivo
    strtok(nome_arquivo, "\n");

    FILE *arq = fopen(strcat(nome_arquivo, ".txt"), "w+");

    if (arq == NULL)
    {
        printf("ERRO");
        system("Pause");
        exit(1);
    }

//Frase que vai dentro do arquivo
    printf("Digite bastante coisa: ");
    fgets(mensagem, MAX, stdin);

    fprintf(arq, "%s", mensagem);

//Ler o que foi digitado e contar as ocorrencia de 'A', 'C', 'G' e 'T'
    printf("\nMensagem dentro do arquivo:\n");
    rewind(arq);
    fscanf(arq, "%s", frase);
    printf("%s\nS",frase);
    fclose(arq);
}

Upvotes: 2

Related Questions