C-duvida!

nunoalex

Power Member
Tou a ter problemas num trabalho.
O problema e o seguinte: tenho um ficheiro em que cada linha tem uma string. Quero ler as strings tds ate nao ter mais no ficheiro. Nao faco a minima como implementar isto. sei que tenho que utilizar um ciclo while para ler tds as strings, e utilizaro fgets para ler cada string (acho eu). Ah.... cada string vai ser guardado num campo de um struct. A struct e do tipo:

typedef struct sString
{
char string [70];
struct sString *seg;
} *String;

Agora nao sei o k por como condicoes de controlo do ciclo, nem o k meter como parametros do fgets.... Agradecia qq ajuda....
Cumps
 
Vê se chegas lá assim...

enquanto não for encontrado o fim de ficheiro(EOF)....ler strings...

é bastante evidente
 
para o fgets...

(man fgets - incompleto)
Código:
NAME
     fgets, gets -- get a line from a stream

LIBRARY
     Standard C Library (libc, -lc)

SYNOPSIS
     #include <stdio.h>

     char *
     fgets(char * restrict str, int size, FILE * restrict stream);

     char *
     gets(char *str);

DESCRIPTION
     The fgets() function reads at most one less than the number of characters
     specified by size from the given stream and stores them in the string
     str.  Reading stops when a newline character is found, at end-of-file or
     error.  The newline, if any, is retained.  If any characters are read and
     there is no error, a `\0' character is appended to end the string.

     The gets() function is equivalent to fgets() with an infinite size and a
     stream of stdin, except that the newline character (if any) is not stored
     in the string.  It is the caller's responsibility to ensure that the
     input line, if any, is sufficiently short to fit in the string.

RETURN VALUES
     Upon successful completion, fgets() and gets() return a pointer to the
     string.  If end-of-file occurs before any characters are read, they
     return NULL and the buffer contents remain unchanged.  If an error
     occurs, they return NULL and the buffer contents are indeterminate.  The
     fgets() and gets() functions do not distinguish between end-of-file and
     error, and callers must use feof(3) and ferror(3) to determine which
     occurred.
exemplo
Código:
char str[20];
FILE* file=fopen(...);

fgets(str,20,file);
 
Ficheiro

BOOL function lerFich(){

FILE *in_file;
char *string;


if((err = fopen_s(&in_file,"meu_ficheiro.txt","r"))!= 0){
printf("Erro ao abrir o ficheiro...");
return FALSE; // NÃO Abri
}

while (!feof(in_file)){
fscanf(in_file,"%s",string);

printf("A string --> %s\n",string); // Faça o processamento que quiser.


}

fclose(in_file);
free(string);

return TRUE; // Terminei com sucesso
}
 
Última edição:
sugiro tb que reformules o struc para algo do genero:

struct _mystring {
char _word[70];
struct _mystring *next;
};
typedef _mystring MYSTRING, *PMYSTRING;
 
Back
Topo