168k views
3 votes
Write a C program that will allow you to add messages to a file that has NO permissions for any user. A Unix system has many files that have sensitive information in them. Permissions help keep these files secure. Some files can be publicly read, but can not be altered by a regular user (ex.: /etc/passwd). Other files can't be read at all by a regular user (ex.: /etc/shadow). The program you develop should take a message given as a command line argument and append it to a file (also specified on the command line). The file should have no permissions, both before and after the message is appended. Of course, the file should be owned by you. Your program should also have a -c option that will clear the file before the message is appended. Algorithm Check to see if the output file exists. If it doesn't, create it. Life is simpler if a newly created file is closed at the end of this step. Check the permissions of the output file. If any permissions exist, print a useful error message and exit. Change the permissions on the file to allow writing by the user. Open the file for output. If the "-c" command line option is present, make sure the file is truncated. Write the message from the command line to the output file. Write an additional newline character so that the output has a nicer format.

User TrevJonez
by
4.2k points

1 Answer

3 votes

Answer:

see explaination

Step-by-step explanation:

#include <iostream>

#include <fstream>

#include <sys/types.h>

#include <sys/stat.h>

#include <time.h>

#include <stdio.h>

#include <stdlib.h>

using namespace std;

int main(int agrc,char*argv[])

{

struct stat sb;

if(agrc != 2){

cout << "invalind command line arguments "<< endl;

return 0;

}

if (stat(argv[1], &sb) == -1) {

perror("stat");

exit(EXIT_FAILURE);

}

if((sb.st_mode & 777) != 0) {

cout<<"file has permission and its invalid"<<endl;

}

//chmod(argv[1], S_IRWXU);

int status = chmod(argv[1], 0200);

if(status){

cout<<"permission sucessfull change"<<endl;

}

ofstream myfile;

myfile.open (argv[1], ios::out | ios::app);

myfile<<argv[2]<<endl;

status = chmod(argv[1], 0000);

if(status){

cout<<"permission sucessfull change

0000"<<endl;

}

myfile.close();

cout << "thank you" << endl;

return 0;

Write a C program that will allow you to add messages to a file that has NO permissions-example-1
User John Harrington
by
4.4k points