2010-03-31 9 views
1

J'ai un fichier texte contenant des mots séparés par un espace. Je veux prendre chaque mot du fichier et le stocker. J'ai donc ouvert le fichier mais je ne sais pas comment affecter le mot à un caractère.Lecture de données à partir d'un fichier texte en C

FILE *fp;
fp = fopen("file.txt", "r");
//then i want
char one = the first word in the file
char two = the second word in the file

Répondre

1

vous ne pouvez pas tenir un mot dans un variable.It char doit être une chaîne ou un pointeur char qui peut être agrandie.

essayez ceci;

char p [10]; // En supposant qu'un mot peut avoir plus de 10 caractères.

FICHIER * fp;

fp = fopen ("fichier.txt", "r");

fscanf (fp, "% s", p);

2

Vous ne pouvez pas affecter un mot à un caractère. Vous pouvez assigner un seul caractère à un caractère - d'où le nom. Vous pouvez affecter un mot à un tableau de caractères - comme s [128].

Par exemple:

 char word[128]; 
    fscanf(fp, "%s", word); 

Remarque, dans le code de production vous ne pouvez pas simplement utiliser un tampon statiquement taille, cela conduira à un débordement du code tampon exploitable.

+0

Vous pouvez utiliser 'fscanf (fp, « % 127s » , word); 'pour éviter le dépassement de tampon dans ce cas. – caf

0

Si vous voulez un peu plus flexible - par exemple: en choisissant les caractères qui identifient un mot - vous pouvez jeter un oeil à ceci:

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

// adjust size for your needs 
#define MAX_WORD_LEN 1000 

static char *parseable_characters_str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxy-"; 
static char parseable_characters_tbl[256] = {0}; // lookup index table, stores yes/no -> allowed/not allowed 

/* 
* builds the lookup table 
*/ 
void build_lookup_index(char *table, const char *str) 
{ 
    int i; 

    // init table to zero 
    memset(table,0,256); 

    // set value to 1 at ASCII-code offset of the array if the character is allowed to be 
    // part of the word 
    for (i=0; str[i]; i++) 
     table[(unsigned char)str[i]] = 1; 
} 

/* 
* returns unparsed bytes (kind of offset for next reading operation) 
*/ 
int parse_buffer(char *buf, int size, const char *lookup_table) 
{ 
    int i,l,s; 
    char word[MAX_WORD_LEN+1]; 

    i = 0; 
    l = 0; 
    s = 0; 

    while (i<size) { 

     // character not in lookup table -> delimiter 
     if (!lookup_table[buf[i]] || !buf[i]) { 
      if (l >= MAX_WORD_LEN) { 
       fprintf(stderr,"word exceeds bounds\n"); 
      } 
      else if (l > 0) { // if word has at least 1 character... 

       // append string-terminator 
       word[l] = '\0'; 
       printf("word found (%d): '%s'\n",l,word); 

      } 

      // reset word length 
      l = 0; 

      // save last word offset 
      s = i+1; 
     } 
     else { 

      // prevent buffer overflows 
      if (l < MAX_WORD_LEN) 
       word[l] = buf[i]; 

      l++; 
     } 

     if (!buf[i]) 
      break; 

     i++; 
    } 

    if (s > 0 && size-s > 0) { 

     // move rest of the buffer to the start for next iteration step 
     memmove(buf,buf+s,size-s); 

     return size-s; 
    } 

    return 0; 
} 

int main(int argc, char *argv[]) 
{ 
    FILE *fh; 
    char buf[1000]; // read buffer 

    // "rb" because of Windows - we want all characters to be read 
    fh = fopen("out.txt","rb"); 

    // initialize word index 
    build_lookup_index(parseable_characters_tbl,parseable_characters_str); 

    if (fh) { 
     int r,off = 0; 
     while (!feof(fh)) { 
      r = fread(buf+off,1,sizeof(buf)-off,fh); 
      off = parse_buffer(buf,r,parseable_characters_tbl); 
     } 
     fclose(fh); 
    } 

    return 0; 
} 
Questions connexes