• C

searching trhough a text file.

I have a text file constisting of lines. Each line has 512 char. I am trying to find a way to make a string search and return the number of line where the string was found. The string is a uniqe number. Any help is appriciated.
Thank you
Carl3003Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

shah1d1698Commented:
How are chars arranged on the file?? i.e are the numbers seperated by spaces or else??
0
Carl3003Author Commented:
yes they are separted by ':'
0
Carl3003Author Commented:
this is a copy of only one line, the other lines are similar
myusername:x:userid:300:fName lName:/data/myuserid:/bin/bash

i am asking the user the enter fName and lName and then i am trying to search by userid and to replace the old fName and lName with new one..
0
Increase Security & Decrease Risk with NSPM Tools

Analyst firm, Enterprise Management Associates (EMA) reveals significant benefits to enterprises when using Network Security Policy Management (NSPM) solutions, while organizations without, experienced issues including non standard security policies and failed cloud migrations

shah1d1698Commented:
steps are..

1. Initialize file pointer.
2. Initialize a variable named lineCounter to zero.
3. Read lines from the txt file and increment the lineCounter at the same time.
4. For each line, parse the whole string into tokens and check against the target string.
5. Report a match with the current value of the lineCounter.  
6. Close the file.


To create tokens of a string, u can use strtok() library function which is defined in string.h header file.
0
shah1d1698Commented:
I'll be away for some time..If u run into any problem implementing the above steps, let us know...
0
Carl3003Author Commented:
ok thanks
0
Carl3003Author Commented:
what i dont understand is how to read a whole line from the file.
0
Carl3003Author Commented:
so far down up to here. Still cant get how i can change the fName and the lName..
 char buf[SIZE];
      printf("new gcos :  ");      
    if( fgets(buf, SIZE, stdin) == NULL)
            exit(1);
      else
        buf[strlen(buf)-1] = '\0';

    int fd = open("passwd", O_RDWR);
      FILE *fp=fopen("passwd","r");
    if(fp==NULL)
    {
            //perror(av[1]); exit(1);
    }
      char line[512];
      char current;
      int count=0;
      while(current = getchar())
      {
            if(current=='\n')
            {
                  if(count==512)
                        exit(1);
                  

                  count=0;
            }
            else
            {
                  line[count]=current;
                  ++count;
            }
      }
0
Carl3003Author Commented:
down=done
0
Carl3003Author Commented:
Also, i forgot to mention but when the user enter fName  lName the program must make sure that the lines doesnt exceed 512 char per line..
0
SadrulCommented:
you can use fgets to read a whole line. you can set the max number of characters to read, so you won't read more than 512 bytes.

you do not need to open and fopen the same file. i would suggest you fopen the file and fgets each line, then do a strstr to see if the substring you are looking for is present in the line.

-- Adil
0
Carl3003Author Commented:
thats done..Any suggestions on how to replace fName and lName with new ones?

FILE *fp=fopen("passwd","r");
    if(fp==NULL)
    {
            //perror(av[1]); exit(1);
    }
      char line[512];
      char current;
      int count=0;
      while(fgets(line, 512, fp)!=NULL)
      {
            char str[10];
            sprintf(str,"%d",getuid());

            if( strstr( line, str)!=NULL)
            {
                  printf("String found");
            }

      }
0
shah1d1698Commented:
Are the new and old fName and IName are of same length ??..if so then following segment can be used to replace a portion from the line..

char *startOfSubStr;
while(fgets(line, 512, fp)!=NULL)
     {
          char str[10];
          sprintf(str,"%d",getuid());

          startOfSubStr = strstr(line, str); //startOfSubStr has the starting location of str in line.
          if( startOfSubStr != NULL)
          {
             strncpy(startOfSubStr, str, strlen(str));//replacement occurs.  
             printf("String found and replaced %s", line);
          }
0
shah1d1698Commented:
To reflect the changes in the file u can create a new file with the changed entries written in it. Then remove the old file and rename the new file with the name of the old file.

Using your code..

FILE *fp=fopen("passwd","r");//for reading the old file
FILE *fp1=fopen("passwd1","w");// for writing the new file
char str[10];
sprintf(str,"%d",getuid());
char *startOfSubStr;
char *line;
while(fgets(line, 512, fp)!=NULL)
     {
          startOfSubStr = strstr(line, str); //startOfSubStr has the starting location of str in line.
          if( startOfSubStr != NULL)
          {
             strncpy(startOfSubStr, str, strlen(str));//replacement occurs.  
             printf("String found and replaced %s", line);
             fputs(line, fp1); //writing to the new file
          }
          else
          {
             fputs(line, fp1); // writing to the new file
          }
     }//end of while

fclose(fp);
fclose(fp1);
remove("passwd"); // removing file named passwd.
rename("passwd1", "passwd"); // renaming passwd1 to passwd.

//This method incurs excessive overhead...
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.