this program writes the user supplied text ( command line arg ) to the specified text file along with the real user id of the user.
problem -> the user id is not visible inside text editor .. but its present when seen using a hexeditor
Code:
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#define FILENAME "/tmp/text"
void usage(char *prog_name, char *filename) {
printf("Usage: %s <date to write to %s>\n", prog_name, filename);
exit(0);
}
int main(int argc, char *argv[]) {
int userid, fd; // file descriptor
char *buffer;
buffer = malloc(100);
if (buffer == NULL)
{
fprintf(stderr, "Error: could not allocate memory.\n");
exit(1);
}
if(argc < 2) // If there aren't commandline arguments
usage(argv[0], FILENAME); // display usage message and exit
strncpy(buffer, argv[1], strlen(argv[1])); // copy into buffer
// Opening the file
fd = open(FILENAME, O_WRONLY|O_CREAT|O_APPEND, S_IRUSR|S_IWUSR);
if(fd == -1)
perror("error while opening file");
userid = getuid(); // get the real user ID
// Writing data
if(write(fd, &userid, 4) == -1) // write user ID before note data
perror("error while writing userid to file");
write(fd, "\n", 1); // terminate line
if(write(fd, buffer, strlen(buffer)) == -1) // write note
perror("error while writing buffer to file");
write(fd, "\n", 1); // terminate line
// Closing file
if(close(fd) == -1)
perror("error while closing file");
free(buffer);
return 0;
}
here is the terminal session
Code:
[rohit@localhost tmp]$ gcc -Wall -o notes notes.c
[rohit@localhost tmp]$ ./notes "this is some line of text"
[rohit@localhost tmp]$ cat /tmp/text
this is some line of text
[rohit@localhost tmp]$ od -c /tmp/text
0000000 364 001 \0 \0 \n t h i s i s s o m
0000020 e l i n e o f t e x t \n
0000037
[rohit@localhost tmp]$ od -x /tmp/text
0000000 01f4 0000 740a 6968 2073 7369 7320 6d6f
0000020 2065 696c 656e 6f20 2066 6574 7478 000a
0000037
[rohit@localhost tmp]$ id
uid=500(rohit) gid=500(rohit) groups=500(rohit) context=user_u:system_r:unconfined_t
[rohit@localhost tmp]$ exit
01f4 is 500 in decimal
thanks
rohit