Read only one line in the file

Asked

Viewed 1,383 times

1

I want fgets,take only one line and not the entire file,how do I do it in C? If I print the word variable in the function it prints everything and also would like to return that line in main.problema

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

int abrir_arquivo(char *palavra){
    FILE *file;

    file=fopen("Frutas forca.txt", "r");
    //se o arquivo for encontrado

    if(file==NULL){
        printf("erro");
    }
    while((fgets(palavra,50,file))!=NULL)
        printf("%s",palavra);

    fclose(file);

}

int main(){
    char palavraforca[50];
    abrir_arquivo(&palavraforca);
    return 0;
}
  • The fgets does it already, it reads up the buffer reach the specified size or find the end of the line or end of the file. If you are not doing this, there is something else wrong. Could [Dit] the question and elaborate a [mcve] including an example of the text you are reading?

  • Ready, edited

  • Only the [mcve] and the example of the text read.

  • Ready, edited

  • Your file function expects to receive an array of characters (this is your address) but you are invoking it by specifying the address of the array as a parameter. Exchange open file(&palavraforca); by open_file(palavraforca);

  • still not printing on main

  • For some reason,.

  • Can you explain what while((fgets(palavra,50,file))!=NULL) ago?

  • It takes a line from the file file and adds it to the 'word' variable with size 50, while it is different from null meaning empty,

  • I may be wrong in the definition of null but I think that’s it

Show 5 more comments

1 answer

1

I think I’d better use the fscanf.

Well, for text files, there are two functions especially to take data from within the file (fscanf()) and to put data into a file (fprintf()).

The structure of fscanf() is: fscanf(file, "data type", variable).
Where:
file: is the pointer to the file set with FILE;
data type: is like normal scanf (%s for string, %d for integer, etc)
variable: is the variable that will store the read value of the file (obligatorily equal to the type of data passed and with "&" before the variable, except for strings).

The structure of fprintf() is: fprintf(file, "data type n", variable).
Where:
file: is the pointer to the file set with FILE;
data type: it is like the normal printf (%s for string, %d for integer, etc., and here it is necessary the " n" in case you want to skip a text line).
variable: is the variable that will store the read value of the file (obligatorily equal to the data type passed).

Your code would look like this:

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

int abrirArquivo(char *palavra); //define apenas o cabeçalho da função. Sem o cabeçalho, a função deve ficar acima do main


int main(){
    char palavraforca[50];

    abrirArquivo(palavraforca);
    printf("%s\n", palavraforca);

    return 0;
}


int abrirArquivo(char *palavra){
    FILE *file;
    if((file=fopen("Frutas forca.txt", "r"))==NULL){ //poupa linha atribuindo e comparando ao mesmo tempo
        printf("ERROR: abrirArquivo fopen == NULL\n"); //informa onde e qual foi o erro
        exit(1); //para o programa nesse ponto.
    }

    fscanf(file, "%s", palavra); //lê uma linha, caso queira mais linhas, use while(!feof(file))

    fclose(file);
    return 0;
}

In your case, you might want to take a specific line, maybe this isn’t even the best way to implement, but here’s a code that takes a specific line from the file:

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

int abrirArquivo(char *palavra, int linha); //define apenas o cabeçalho da função. Sem o cabeçalho, a função deve ficar acima do main


int main(){
    char palavraforca[50];
    int linha;

    linha=1; //para pegar a palavra na primeira linha
    abrirArquivo(palavraforca, linha);
    printf("Linha 1: %s\n", palavraforca);

    linha=2; //para pegar a palavra na segunda linha
    abrirArquivo(palavraforca, linha);
    printf("Linha 2: %s\n", palavraforca);

    linha=3; //para pegar a palavra na terceira linha
    abrirArquivo(palavraforca, linha);
    printf("Linha 3: %s\n", palavraforca);

    return 0;
}


int abrirArquivo(char *palavra, int linha){
    FILE *file;
    if((file=fopen("Frutas forca.txt", "r"))==NULL){ //poupa linha atribuindo e comparando ao mesmo tempo
        printf("ERROR: abrirArquivo fopen == NULL\n"); //informa onde e qual foi o erro
        exit(1); //para o programa nesse ponto.
    }

    /*
    define cont como 0 linhas, a partir da hora que é lida a primeira linha, cont fica com 1 e 
    caso queira pegar a linha 1 o laço é parado, pois cont agora é igual a linha
    */
    int cont=0;
    while(cont!=linha){
        fscanf(file, "%s", palavra); //lê uma linha
        cont++;
    }

    fclose(file);
    return 0;
}

Any more questions just ask. Good luck and good studies.

Browser other questions tagged

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