tags:

views:

161

answers:

5

I'm reading a file in C, char by char but I need to get 2 consecutive chars. Please, can someone suggest me some options?

the main idea of the program is to read a source C file and to find the number of all significant chars (ignore ws) and to ignore '*/' & '/*'. I'm trying to write the program in really basic level because it is for course work for friend of mine. In general I'm PHP programmer.

This is the full code I managed to write.

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

int in_array(char *array, char searchedEl);
int main(){
  FILE *fp;
  char readChar;
  char exeptChars[] = {'\n', '\t','\0'};
  int charsCounter = 0;
  char *openComment = "/*";
 char *closeComment = "*/";
 char tempHolder[2];
 int j=0;
  fp=fopen("testrw.txt","r");
  if(!fp){
    printf( "Could not open file\n" );
    return 1;
  }
  while( (readChar = fgetc(fp)) != EOF ){
    if((readChar == '*') || (readChar == '/') || (readChar == '\\')){
      if(j < 1){
    tempHolder[j] = readChar;
    j++;
    continue;
      }
      else{
    tempHolder[j] = readChar;
    if(strcmp(tempHolder, openComment) || strcmp(tempHolder, closeComment)){
      charsCounter += 2;
    }
    tempHolder[2]='\0';
    j=0;
    continue;
      }
    }   

    if(!in_array(exeptChars, readChar)){
      printf("Permited char: %c\n", readChar);
      charsCounter++;
    }
  }
  printf("Characters %d\n", charsCounter+1);
  return 0;
}
int in_array(char *array, char searchedEl){
  char tempEl;
  int i=0;
  while(tempEl = array[i]){
    if(tempEl == searchedEl){
      return 1;
    }
    i++;
  }
  return 0;
}
+1  A: 

fread() will allow you to fetch multiple bytes in a single operation.

Adam Luchjenbroers
A: 

Take the else{} out of the if() (and, of course, convert it to if(j==1))

Pavel Radzivilovsky
A: 

use

size_t fread ( void * ptr, size_t size, size_t count, FILE * stream );

ptr - Pointer to a block of memory with a minimum size of (size*count) bytes. size - Size in bytes of each element to be read. count - Number of elements, each one with a size of size bytes. stream - Pointer to a FILE object that specifies an input stream. size_t - The total number of elements successfully read.

wrapperm
+1  A: 

Use ungetc(readChar,fp) if the next character is wrong:

char get_token(){
    readChar = fgetc(fp);
    if(readChar==EOF) return END_OF_FILE;
    if(readChar=='/'){
        nextChar=fgetc(fp);
        if(nextChar==EOF) return readChar;
        if(nextChar=='*') return OPEN_COMMENT;
        ungetc(nextChar,fp);
    }
}
Antony Hatchkins
I'll tray that :)
bozhidarc
A: 

It seems that you are re-inventing the wheel. Parsing text char-by-char is something you shouldn't do unless you are doing some thing very low-level.

I think it is better to use some text parsing libs (GNU regex?)

From what I understand is that you are searching for comments in C code. If you want to parse C code there is many ways to do it better than parsing it by char-char parsing.

Yousf