Search code examples
cstringbufferstdio

read and jump lines from a file C


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

int main(int argc, char* argv[]) {
  FILE* file = fopen("questions-words.txt", "r"); 
  char line[256];

  while (fgets(line, sizeof(line), file) != NULL) {                
    if (line[0]==":") {
      continue;
    }
    printf("%s", line);   
  }
  fclose(file);
  return 0;
}

Hi I trying to print the lines of a file and jump the ones that start with a ":" but it doesnt seem to work. Also I can't print line[0] it gives a warning because "line is type int"


Solution

  •     #include <stdio.h>
        #include <string.h>
    
    
        int main(int argc, char* argv[])
        {
    
    
            FILE* file = fopen("questions-words.txt", "r"); /* should check the result */
            if (file==NULL){
                return-1;
            }
            char line[256];
            char first[20],second[20],third[20],fourth[20],temp[20];
    
    
            while (! feof(file)) {
                fscanf(file,"%s \t", first);
                if (!strcmp(first,":")){
                    fscanf(file,"%s \t",temp);
                continue;
                    }
    
                    fscanf(file,"%s \t", second);
                    fscanf(file,"%s \t", third);
                    fscanf(file,"%s \t", fourth);
                    printf("%s %s %s %s \n", first, second, third, fourth);
    
    
    
            }
                    fclose(file);
    
                    return 0;
        }
    

    @ameyCu 's answer is better but since I knew each line had 4 words I also find this solution (just in case is helpful for somene)