1834200 Members
2818 Online
110066 Solutions
New Discussion

open file in C

 
SOLVED
Go to solution
jim bidebo
Regular Advisor

open file in C

want to open a file (/pidfile) and get the information from it into a char (named pid). got access to hp-ux 10 standard cc and gcc.

could anyone please help me with this?
3 REPLIES 3
A. Clay Stephenson
Acclaimed Contributor
Solution

Re: open file in C

Hi:

Your question is very unclear but I am going to assume that this is a textfile.

#include

#define PIDFILE "/pidfile"

FILE *f = NULL;

f = fopen(PIDFILE,"r");
if (f != NULL)
{
char pid[80],*p = NULL;

pid[0] = '\0';
p = fgets(pid,sizeof(pid),f);
(void) fclose(f);
}
else (void) fprintf(stderr,"Can't open %s\n",PIDFILE);

Note: pid in this case may have a Linefeed on the end; you may need to strip it off.

If it ain't broke, I can fix that.
harry d brown jr
Honored Contributor

Re: open file in C

#include
#include

char *pidinfo;

main()
{

FILE *input_file;
input_file = fopen("./pidfile","r");

fscanf(input_file,"%s",&pidinfo);
printf("%s\n",&pidinfo);
exit(0);
}

As Clay said, without knowing what the "/pidfile" looks like, I'm going to assume it's a normal pidfile like syslogd's.

live free or die
harry
Live Free or Die
jim bidebo
Regular Advisor

Re: open file in C

thanks for all the help
heres my complete solution:

#include /* needed for printf, fscanf and fopen */
#include /* needed for atol */
#include /* needed for kill */
static char *pidinfo;
main()
{
int sig=9; /* declare wich signal kill() will use */
long pid=0;
FILE *input_file;
input_file = fopen("/pidfile","r"); /* open file */

fscanf(input_file,"%s",&pidinfo); /* read file */

pid=atol(&pidinfo); /* convert char pid to long pid (needed by kill()) */
printf("killing %d\n",pid); /* some nice output for before killing */
kill(pid, sig); /* killing */
exit(0);
}