Deleting a file using a FILE * [duplicate] - c

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How can I delete a file pointed to by a FILE* in C?
I want to delete a file at the end of a C program, by which point the filename has been long forgotten. It would be nice if I could just use the FILE * to delete it directly or find the filename and then use remove()... rather than having to memorize the filename for this.
Does anybody know of any ways in which this could be achieved? I am on a Windows system, but I need to maintain portability so can't use any OS specific stuff.

nice if I could just use the FILE * to delete it directly or find the
filename and then use remove()... rather than having to memorize the
filename for this
There's no way to retrieve the file name from a FILE *. A FILE * isn't necessarily a real file; just think of popen(3) for example.

I do not know of a portable way, but there is a Linux version (which might work on other unices) and a Windows version:
Linux: a readlink() on sprintf("/proc/self/fd/%d",fd) should work
Windows: GetFileInformationByHandleEx() will give you the name as part of a struct (Search MSDN, don't have the details in my head)

E.g
#include <stdio.h>
#include <stdlib.h>
void endproc(void){
remove("removeFile.dat");
}
int main(){
atexit(endproc);
return 0;
}

Related

Opening a C library header file in Vim

Say I'm including a header file in vim while writing a C program, e.g
#include <time.h>
I have no idea what structures or functions are declared there. How can I jump to that file and open it in Vim? Is there any way to do that?
On Unix-like systems, Vim is already wired for C by default so you only have to move the cursor to <time.h> and press gf, to open the header in the same window or <C-w>f to open it in a new window.
See this answer to a similar question that was asked a few hours ago for additional pointers.
You can use:
find . -name "time.h"
to find the file and then you can copy the path and open it with vim.
But this this won't really help, because its not as structured as you might think it is. To learn more about time.h I would google it. There are several websites explaining structs, functions etc.
For example: https://www.tutorialspoint.com/c_standard_library/time_h.htm

c programming how to convert system output to char [duplicate]

This question already has answers here:
How do I execute a command and get the output of the command within C++ using POSIX?
(12 answers)
Closed 7 years ago.
I was wondering if anyone can help me:
I need to turn the output of the system command : whoami into a variable.
Example:
char *a;
a = system("whoami");
printf("username = %s",a);
I have tried a few methods such as printing the commands output to a text file like: whoami >> output.txt and than making the program read from that file, however i am encountering errors through that method. I also consider that method to be a little messy and unnecessary as im positive that there must be a way within C to let me do this.
This question may be a duplicate so please label as necessary(but also answer if capable)
Thanks a lot :)
If everything you want is to read an environment variable in a POSIX environment, you can simply call getenv:
http://man7.org/linux/man-pages/man3/getenv.3.html
#include <stdlib.h>
#include <stdio.h>
int main() {
char* username = getenv("USER");
printf("username = %s\n", username);
return 0;
}
If you want something more complex, you can use popen:
http://man7.org/linux/man-pages/man3/popen.3.html to create a pipe to a process and read from stdout, this answer should help in that case:
C: Run a System Command and Get Output?
This should do the trick. I haven't tested it myself, but I checked and its listed in the Linux man pages so I'm sure its kosher.

Keeping fileowner and permissions after copying file in C

here is my problem: In C, I create the copy of a file (with some changes) This is done trivially via fopen(), getchar and putchar.
Copying the file is fine and the outputfile itself is what I want it to be.
My problem is: I assume that I will use this program often as sudo and then the resulting file has both another owner (root) as well as different permissions (execute rights are gone).
My question is: How can I copy the owner and permissions of the original file and then write them into the new one?
Use the fstat(2) system call to obtain the details about the owner and the permissions, and the fchmod(2) and fchown(2) system calls to set them. See an example in the setfile function of the *BSD cp(1) source code.
since you use fopen():
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
//fp is your source filepointer, fdest is your dest filepointer
//fn is the new filename you're copying to
struct stat fst;
//let's say this wont fail since you already worked OK on that fp
fstat(fileno(fp),&fst);
//update to the same uid/gid
fchown(fileno(fdest),fst.st_uid,fst.st_gid);
//update the permissions
fchmod(fileno(fdest),fst.st_mode);
as a quick note, you may want to fread() and fwrite() instead of f*char()'ing
Under linux use the libc fchmod and fchown
Manpages can be found here:
http://linux.die.net/man/2/fchmod
http://linux.die.net/man/2/fchown

How to remove multiple files in C using wildcards?

Is there any way in C to remove (using remove()) multiple files using a * (wildcards)?
I have a set of files that all start with Index. For example: Index1.txt, Index-39.txt etc.
They all start with Index but I don't know what text follows. There are also other files in the same directory so deleting all files won't work.
I know you can read the directory, iterate each file name, read the the first 5 chars, compare and if it fits then delete, but, is there an easier way (this is what I currently do by the way)?
This is standard C, since the code runs on Linux and Windows.
As you point out you could use diropen, dirread, dirclose to access the directory contents, a function of your own (or transform the wildcards into a regex and use a regex library) to match, and unlink to delete.
There isn't a standard way to do this easier. There are likely to be libraries, but they won't be more efficient than what you're doing. Typically a file finding function takes a callback where you provide the matching and action part of the code. All you'd be saving is the loop.
If you don't mind being platform-specific, you could use the system() call:
system("del index*.txt"); // DOS
system("rm index*.txt"); // unix
Here is some documentation on the system() call, which is part of the standard C library (cstdlib).
Is this all the program does? If so, let the command line do the wildcard expansion for you:
int main(int argc, char* argv[])
{
while (argc--)
remove(argv[argc]);
}
on Windows, you need to link against 'setargv.obj', included in the VC standard lib directory.

Determine UID that last modified a file in Linux?

I'm writing a program that will be monitoring select files and directories for changes. Some of the files are world writeable, some owner, some group.
What I need to do is be able to figure out the last person to modify (not just access) a file. Somehow I thought this would be simple, given that we know the inode of the file .. however I can not seem to find any way of obtaining this. I thought there was a practical way of correlating any given inode to the uid last accessing it.
I think I've squeezed google for all its going to give me on the topic.
Any help is appreciated. I'm writing the program in C.
Edit:
I need to be able to do this after the PID of whatever program modified the file is long gone.
If you are on a 2.6 kernel, you can take advantage of kernel's auditd daemon. Check this URL out. It might give you some hint on how to accomplish what you are trying to. I'm sure there is an API you could use in C.
To my knowledge, this information is not stored by any of the common filesystems, but you should by able to hook into inotify and keep an audit trail of which processes touch which files.
Okay, using straight old standard Linux with normal file systems, you're not going to be able to do it. That information isn't stored anywhere (see man lstat for what is stored.)
As #pablo suggests, you can do this with security auditing turned on. The link he notes is a good start, but the gist of it is this:
you turn on the audit daemon, which enables auditing form the kernel
you configure the rules file to capture what you want
you search the audit files for the events you want.
The difficulty here is that if you start auditing all file operations for all files, the audit is going to get big.
So what is the actual need you want to fil?
very basic , but it works:
you can easily write a little c-program that does what you want
this example retrieves the UID of file or directory or link,
just try to find the properties that you want.
compile with:
gcc -x c my-prog.c -o my-prog
then:
./my-prog /etc
a lot of other information can be obtained like this
it's not robust. but whatever, i know how to use it,
and do the checking in a bash shell :-)
[ -x /etc ] && my-prog /etc
source code:
# retrieve the uid of a file
# source code: my-prog.c
#
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
int main(int argc, char **argv) {
struct stat buffer;
int status;
char *fname;
fname=argv[1];
status = stat(fname, &buffer);
printf("%i",buffer.st_uid);
return 0;
}

Resources