String is not being saved to a text file

Asked

Viewed 30 times

-1

I made this code whose purpose is to read any string (Maximum size 30), and to write this string in a text file. After reading the string, the program is terminated normally (No errors), but when checking the file "test.txt", note that nothing is being written to it. How can I solve this problem?

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

int main() {
    FILE *arq;
    int i;
    char nome[30];

    arq = fopen("teste.txt","w");

    if(arq = NULL){
        printf("Não é possível utilizar este arquivo");
        return 0;
    }

    printf("Informe um nome:");
    scanf("%s",nome);

    for(i = 0; i < strlen(nome); i++)
        fputc(nome[i], arq);

    fclose(arq);
    return 0;
}
  • I don’t see anything wrong with your show. The only thing to note is that if you want to effectively save a string then it is missing to save the ending ' 0' character.

1 answer

1


The if you put is setting the file pointer to null instead of checking if it is null. if(arq = NULL) Exchange for: if(arq == NULL)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.