Reading Lines (c in linux)

Discussion in 'C' started by xaykogeki, Apr 13, 2010.

  1. xaykogeki

    xaykogeki New Member

    Joined:
    Apr 13, 2010
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    Good day,

    I have a text file with this kind of input.

    5 ABCDE
    1000 ABBBB
    1001 BCCDA

    Can somebody help me start on how I will read the first line only where the first number
    signifies the number of questions, then the next one will be the correct answer.

    the second line is the ID No and the answer of that person and compare it?

    I know I have to make a struct for the 2nd line and the succeeding lines, but how can I skip the first line?

    how can I also check each and every character using char?

    thanks
     
  2. Poonamol

    Poonamol New Member

    Joined:
    Mar 31, 2010
    Messages:
    33
    Likes Received:
    0
    Trophy Points:
    0
    You can write a Parse line fumnction which reads each line from file.

    For example,
    file.txt contains....
    ABC123;12344567
    PQR678;45304912
    etc....

    Code:
    int  iLenName;
    int  iPosValue;
    int  iLenValue;
    char pLine[BUFFER*2]= {0};
    char pClientNo[CLIENT_NO]= {0};
    char pCommitDate[DATE_LEN+1]	= {0};
    FILE fptr = fopen("file.txt", "r");
    if (fptr == NULL)
    {
    while (fgets(pLine, 500, fptr))
       {
       if (parseLine(pLine, &iLenName, &iPosValue, &iLenValue))
        {
           strncpy(pClientNo, pLine, iLenName);
           pClientNo[iLenName] = '\0';
     
           strncpy(pCommitDate, pLine + iPosValue, iLenValue);
           pCommitDate[iLenValue] = '\0';
        }
    int parseLine(char * pLine,
          int  * pLenName,
          int  * pPosValue,
          int  * pLenValue)
    {
      int  i         = 0;
      while (pLine[i] && pLine[i] != ' ' && pLine[i] != '\t' &&
             pLine[i] != ';' && pLine[i] != '#')
      {
        i++;
      }
      if (i == 0)
      {
        return 0;
      }
      *pLenName = i;
      while (pLine[i] && (pLine[i] == ' ' || pLine[i] == '\t'))
      {
        i++;
      }
      if (pLine[i++] != ';')
      {
       return 0;
      }
      while (pLine[i] && (pLine[i] == ' ' || pLine[i] == '\t'))
      {
        i++;
      }
      *pPosValue = i++;
      while (pLine[i] && pLine[i] != '\n' && pLine[i] != '"')
      {
        i++;
      }
      *pLenValue = i - *pPosValue;
      return 1;
    }
     
    Last edited by a moderator: Apr 29, 2010

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice