Alexander Demerdzhiev
Alexander Demerdzhiev

Reputation: 1044

Reading only first character of each line in file

I'm currently trying to read and process only first character in each line of a ".c" file. So far i have came to this code, but n is not even printed ot od the loop:

void FileProcess(char* FilePath)
{
    char mystring [100];
    FILE* pFile;
    int upper = 0;
    int lower = 0;
    char c;
    int n =0;
    pFile = fopen (FilePath , "r");
    do {
      c = fgetc (pFile);
      if (isupper(c)) n++;

    } while (c != EOF);

    printf("6");
    printf(n);
    fclose (pFile);
}

Upvotes: 1

Views: 12883

Answers (1)

Floris
Floris

Reputation: 46365

A few points:

  1. You are not printing n correctly. You are feeding it to printf as the "formatting string". It is surprising that you get away with it - this would normally cause havoc.
  2. You are reading one character at a time. If you want to print only the first character of each line, better read a line at a time, then print the first character. Use fgets to read entire line into a buffer (make sure your buffer is big enough).

Example (updated with inputs from @chux - and instrumented with some additional code to aid in debugging the "n=1" problem):

void FileProcess(char* FilePath)
{
    char mystring [1000];
    FILE* pFile;
    int upper = 0;
    int lower = 0;
    char c;
    int n =0;
    pFile = fopen (FilePath , "r");
    printf("First non-space characters encountered:\n")
    while(fgets( myString, 1000, pFile) != NULL)
      int jj = -1;
      while(++jj < strlen(myString)) {
        if ((c = myString[jj]) != ' ') break;
      }
      printf("%c", c);
      if (isupper(c)) {
         printf("*U*\n"); // print *U* to show character recognized as uppercase
         n++;
      }
      else {
         printf("*L*\n"); // print *L* to show character was recognized as not uppercase
      }
    }

    printf("\n");
    printf("n is %d\n", n);
    fclose (pFile);
}

NOTE there are other more robust methods of reading lines to make sure you have everything (my favorite is getline() but it is not available for all compilers) . If you are sure your code lines are not very long, this will work (maybe make the buffer a bit bigger than 100 characters though)

Upvotes: 3

Related Questions