I'm writing a program that will read from /etc/passwd and output the username and shell.
For example, here is the first line of the /etc/passwd file:
root:x:0:0:root:/root:/bin/bash
I need to only output the user and the shell. In this instance it would print:
root:/bin/bash
The values are separated by ':' so I just need to print the string before the first ':' and the string after the 6th ':'
Here is the code I have so far:
#include <string.h>
#define BUFFERSIZE 4096
int printf(const char *text, ...);
int main(void) {
int fd;
int buff_size = 1;
char buff[BUFFERSIZE];
int size;
fd = open("/etc/passwd", O_RDONLY);
if (fd < 0) {
printf("Error opening file \n");
return -1;
}
size = strlen(buff - 17);
size = size + 1;
while ((size = read(fd, buff, 1)) > 0) {
buff[1] = '\0';
write(STDOUT_FILENO, buff, size);
}
}
(I am creating prototypes for printf because one of the requirements was to write the program without including <stdio.h> or <stdlib.h>)
open()instead of a file-streamFILE*andfopen()which makes reading line-oriented input much much easier. Reading withfgets()instead ofread()and then usingstrtok()(or juststrchr()and a counter) would make the task quite easy.size = strlen(buff-17);passes an address that is not yours to play with to a library function expecting an address of a null terminated string... Off to a bad start... The constraint "don't use these header files" probably means "don't use the functions found in these libraries"... Dangerous to provide your own "hand made" function prototypes for standard library functions...buffin uninitialized which would invoke Undefined Behavior in your call withstrlen()(for a 2nd reason...))strchr()andstrrchr()to find the first and the last 'colon' in the buffer you've loaded. Those are the two that are interesting to this assignment...awk -F: '{print $1":"$7}' /etc/passwd