0

I have a script that generates a table from /etc/passwd and names this passwd.idx. My goal is:

1- Load file passwd.idx dynamically

2- Read account name from standart input until end of the file

3- retrieve corresponding record using ISAM method

4- display home directory and login shell of account

I have very similiar code that doing the fisrt 3 goals:

struct part

typedef struct { // idx file record structure
    char actname [32+1];   // account name string +'\0'
    long int pwdoffset;    // passwd file offset
    int  rel;              // record length in ./passwd
} IdxRec, *pIdxRec;

 

Main function

int fidx, fpwd, idxsize = 0, pwdsize, i = 0, ret , j, comfieldsize;
    char actname[32+1], *buf, searchItem[32+1], *s, *str, *oldstr, *old, *new;
    IdxRec idx;
    pIdxRec table;

    
    fidx = open("pwd.idx", O_RDONLY); //open index file
    fpwd = open("passwd", O_RDONLY); //open passwd for read
    
    pwdsize = lseek(fpwd, 0, SEEK_END); // get passwd size
    lseek(fidx, 0, SEEK_SET); //set position 0 for index file
    table = malloc(sizeof(IdxRec) * idxsize); // dinamic memory allocation

    while((ret = read(fidx, &idx, sizeof(IdxRec))) > 0) // get accounts from index file
    {   
        for(j = 0; j < 32+1; j++)
        table[idxsize].actname[j] = idx.actname[j];
        table[idxsize].pwdoffset = idx.pwdoffset;
        lseek(fidx, 0, SEEK_CUR);
        idxsize++;
    }

    new = malloc(sizeof(char) * PWDRLEN); 
    oldstr = malloc(sizeof(char) * PWDRLEN);
    lseek(fpwd, 0, SEEK_SET);
    buf = malloc(sizeof(char) * pwdsize); // dinamic memory allocation for passwd
    read(fpwd, buf, pwdsize);

    printf("Enter Account Name: "); 
    scanf("%s", &searchItem); 

I think this code does the first 3 problem. ISAM is not important at the moment. But I stuck the getting home directory and login shell. What should i need to add this code?

  • This is a duplicate question to https://stackoverflow.com/questions/2910377/get-home-directory-in-linux -- Note: The other question has answered your question – natersoz Nov 08 '20 at 18:59
  • I implement the same structure as `for(i = 0; i < idxsize; i++){ if((homedir = getenv(idx)) == NULL){ homedir = getpwuid(getuid())->pw_dir; printf("%s\n", homedir); break;} if(i == idxsize - 1) { puts("Account not found"); } }` But there is no output – Levent Kaya Nov 08 '20 at 19:16
  • Code in comments is borderline illegible. If it's useful include that as an edit to your question where it can be formatted properly. – tadman Nov 08 '20 at 19:44
  • There's a lot of `32+1` in here where some kind of constant would be better. You should also try and avoid declaring a heap of variables at the top of your function and instead declare them *if* and *when* they're used. Like `int fidx = open(...)` is way better than having to look back and see what type `fidx` is declared as to verify that is correct. – tadman Nov 08 '20 at 19:45

0 Answers0