Hi following code sample seems to have some problem or either it has to do something with OS internals.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
static void usage();
#define MONC_AM_CONF "/tmp/monc.conf"
int main(int argc, char **argv)
{
int ch;
char list[200];
int len;
int fd;
memset(list,0,200);
if (argc < 11) {
usage();
exit(1);
}
while ((ch = getopt(argc, argv, "N:S:P:H:R:")) != -1) {
switch (ch) {
case 'N':
len = strlen(optarg) + 2;
sprintf(list,"%s::",optarg);
break;
case 'S':
sprintf(list+len,"%s::",optarg);
len = len + strlen(optarg) + 2;
break;
case 'P':
sprintf(list+len,"%s::",optarg);
len = len + strlen(optarg) + 2;
break;
case 'H':
sprintf(list+len,"%s::",optarg);
len = len + strlen(optarg) + 2;
break;
case 'R':
sprintf(list+len,"%s ",optarg);
len = len + strlen(optarg);
break;
default:
printf ("You specified a parameter I don't "
"know about.\n");
break;
}
}
argc -= optind;
argv += optind;
printf("Total length of string is %d\n",len);
printf("The string is %s\n",list);
fd = open(MONC_AM_CONF, O_WRONLY|O_CREAT|O_APPEND, 0644);
lseek(fd, 0,SEEK_END);
write(fd,list,len);
close(fd);
return 0;
}
static void usage()
{
printf("Please provide the command in correct format\n");
printf("monc_am_config -N <Comp_Name> -S <Start Script Path> -P <Stop Script Path> -H <HealthCheck Script Path> -R <Recovery Policy>\n");
return ;
}
When I am issuing commands I am getting the output file each time different.
I am expecting execution of this program each time should write the information in the new line but it is writing into the same line in the file.
Plz help.
You should append "\n" to list, i.e
list[len++] = '\n';
Related
here is my code down below, the code is incomplete, but the problem is I have set the t as the only option I have for this program, and when i run it with option -t input, it gives me error as following:
./run: invalid option -- 't'
Option error !
there is my code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <error.h>
#include <string.h>
#define FALSE 0
#define TRUE 1
#define DEFAULT_SECOND 10
extern int errno;
int errnum;
FILE* fin = NULL;
int main (int argc, char* argv[])
{
int opt;
int tFlag = FALSE;
int defaultFlag = TRUE;
int sec;
while ((opt = getopt(argc,argv,"t:"))!=-1)
{
switch (opt)
{
case 't':
tFlag = TRUE;
defaultFlag = FALSE;
break;
case '?':
Printf("No such option, Now taking Exit...");
exit(EXIT_FAILURE);
default:
break;
}
}
for (int i = 0; i < argc - optind; ++i)
{
fin = fopen(argv[optind + i], "r");
if (fin == NULL)
{
errnum = errno;
fprintf(stderr, "Error opening file: %s\n", strerror(errnum));
exit(1);
}
if (defaultFlag == TRUE)
{
sec = defaultFlag;
}
if (tFlag == TRUE)
{
if((sec = atoi(optarg)==-1))
{
printf("input error!!");
exit(EXIT_FAILURE);
}
}
}
return 0;
}
please tell me if I have wrongfully set the option for -t, if possible please tell me where is the problem.
Hello I'm working on a program that prints all the characters like a cat program by using the POSIX functions, the program has to get more than one file when it does it writes the characters of all files in the destination file.
For example;
mycat.exe x.txt y.txt z.txt dest.txt
means write all the characters from x.txt, y.txt and z.txt in order to the file destination dest.txt that it's created after we run the program.
If any file not exits the program will not exit it prints a report that
file not exists
If any error occur, you have to exit the program.
When I compile it it compiles without any error(I'm compiling it in Windows 10), but when i try to run it it shows an error.
This is how I compile it:
gcc -o mycp.exe mycp.c
This is how i run it:
mycp.exe x.txt y.txt z.txt dest.txt
This is the error:
copy: Bad file descriptor
This is the code inside the mycp.c:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#define BUFSIZE 1024
void exit_sys(const char* msg)
{
perror(msg);
exit(EXIT_FAILURE);
}
void exit_fail(const char* msg)
{
fprintf(stderr, "%s\n", msg);
exit(EXIT_FAILURE);
}
void remove_dest_file(int fd, char** argv, int i)
{
_close(fd);
unlink(argv[i]);
}
int copy_file(int fdd, int fds)
{
char buf[BUFSIZE];
int n;
while ((n = read(fds, buf, BUFSIZE)) > 0)
{
_write(fdd, buf, n);
}
if (n < 0)
{
return n;
}
return 0;
}
int main(int argc, char** argv)
{
int fds, fdd;
int n;
char buf[BUFSIZE];
int ch;
int flags;
int argcm1;
int i;
flags = _O_WRONLY | _O_CREAT;
if (argc < 2)
exit_fail("usage:mycp.exe file1.exe file2.exe file3.exe ... filen filedest.exe");
argcm1 = argc - 1;
if (!access(argv[argcm1], F_OK)) {
printf("The file %s exists. Do you want to overwrite?[y]\n", argv[argcm1]);
ch = getchar();
if (ch == 'y' || ch == 'Y')
flags |= _O_TRUNC;
else
exit(EXIT_SUCCESS);
}
if ((fdd = _open(argv[argcm1], flags, _S_IREAD | _S_IWRITE)) < 0)
{
exit_sys("open for destination");
}
for (i = 0; i < argcm1; ++i)
{
if (fds = _open(argv[i], _O_RDONLY) < 0)
{
remove_dest_file(fdd, argv, argcm1);
exit_sys("open");
}
if (copy_file(fds, fdd) < 0)
{
remove_dest_file(fdd, argv, argcm1);
exit_sys("copy");
}
_close(fds);
}
printf("Succes");
_close(fdd);
return 0;
}
I've been working on code that:
1. checks if "sample.txt" exist, if not ,generate a new file,
2. if file already exist, check if first line has single '0'. if not, truncate and write '0'
Below is what i've written so far. however the iszeroOrnewfile always turns into 0 so don't go into different case. Am i approaching this correctly?
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#define buf 128
int main (int argc, char** argv)
{
int fd;
char buff[buf]={0} ;
int iszeroOrnewfile=1;
int iszero=0;
if(!(argv[0]>0))
printf("insert positive integer");
fd = open("./sample.txt",O_RDWR|O_CREAT);
pread ( fd,buff,buf,0);
for (int i=0;i<buf;i++)
{
if((0 != buff[i]) || ('0' != buff[i]) )
{ iszeroOrnewfile = 0;}
if('0' == buff [i]);
{ iszero = 1;}
}
if (iszeroOrnewfile == 1 )
{
if (iszero !=1)
write(fd, "0",strlen("0"));
}
else if(iszeroOrnewfile ==0)
{
truncate ("./sample.txt" , 0);
write(fd, "0",strlen("0"));
}
}
Following code may be useful:
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#define buf 128
int main (int argc, char** argv)
{
int fd;
char buff[buf]={0} ;
int iszeroOrnewfile=1;
int iszero=0;
int isFileCreated = 0;
int len = 0;
int i;
if(!(argv[0]>0))
printf("insert positive integer");
fd = open("./sample.txt",O_RDWR);
if(fd==-1 && errno==ENOENT)
{
//File dosen't exists
isFileCreated = 1;
fd = open("./sample.txt",O_RDWR|O_CREAT);
write(fd, "0",strlen("0"));
}
else
{
len = pread ( fd,buff,buf,0);
for (i=0;i<len;i++)
{
if((0 == buff[i]) || ('0' == buff[i]) )
{
iszero = 1;
break;
}
}
if(len==-1 || iszero)
{
truncate ("./sample.txt" , 0);
write(fd, "0",strlen("0"));
}
}
return 0;
}
I have to programm a TCP/UDP Server/Client software.
Possible arguments: -u: UDP -t: TCP -l Server -p: [Port] -h [IP]
I wrote a function printflags, to see if everything works fine.
The u-, t-, l- and p-Options work fine. But my IP is everytime NULL.
Where is the problem?
#include <ctype.h>
#include <stdio.h>
#include <getopt.h>
#include <stdlib.h>
#include <unistd.h>
int printflags(int, int, int, char *,char *);
int main(int argc, char *argv[]){
int uflag=0;
int tflag=0;
int lflag=0;
char *pvalue = NULL;
char *hvalue = NULL;
int c;
opterr = 0;
while((c = getopt (argc, argv, "utlhp:")) != -1)
{
switch(c)
{
case 'u':
uflag = 1;
break;
case 't':
tflag = 1;
break;
case 'l':
lflag = 1;
break;
case 'p':
pvalue = optarg;
break;
case 'h':
hvalue = optarg;
break;
case ':':
fprintf(stderr, "case :");
case '?':
if(optopt == 'p' || optopt == 'h')
fprintf(stderr, "Option '-%c' requires an argument.\n", optopt);
else if (isprint(optopt))
fprintf(stderr, "Unknown option character '-%c'.\n", optopt);
else
fprintf(stderr, "Unknown option character '%x'.\n", optopt);
return 1;
default:
abort();
}
}
printflags(uflag, tflag, lflag, pvalue, hvalue);
return 0;
}
int printflags(int uflag, int tflag, int lflag, char* pv, char *hv){
printf("-u UDP: %d\n", uflag);
printf("-t TCP: %d\n", tflag);
printf("-l Listen Socket - Server: %d\n", lflag);
printf("-p Port: %s\n", pv);
printf("-h IP: %s\n", hv);
return 0;
}
Your option string should be "utlh:p:". You need a colon after each letter that takes an optarg.
Your parameter to getopt() needs a colon after the h to signify that -h needs an argument.
while((c = getopt (argc, argv, "utlh:p:")) != -1)
// ^ --- here
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
int c, n, E, b, s, v, t, opt, valid = 0;
char current = '\0';
char previous = '\0';
FILE *fp;
/* -n numbers lines
* -E appends a dollar sign to line ends
* -b numbers only non-blank lines
* -s squeezes multiple blank lines down to 1
* -v displays control chars, excluding tab
* -t includes tab in the above
* -e is the same as -E and -v
*/
int setFlags(int argc, char *argv[]) {
int op;
while ((op = getopt(argc, argv, "nEbsvte")) != -1) {
switch (op) {
case 'n': {
n = 1;
break;
} case 'E': {
E = 1;
break;
} case 'b': {
b = 1;
break;
} case 's': {
s = 1;
break;
} case 'v': {
v = 1;
break;
} case 't': {
t = 1;
break;
} case 'e': {
E = 1;
v = 1;
break;
} case '?': {
//fprintf(stderr, "Option `-%c` is not valid.\n", optopt);
return EXIT_FAILURE;
} default: {
abort();
}
}
}
opt = optind;
if(n == 1) {
b = 0;
}
return EXIT_SUCCESS;
}
int checkFile(char *path) {
if (access(path, R_OK) == 0) {
return EXIT_SUCCESS;
} else {
fprintf(stderr, "cat: %s: %s\n", argv[i], strerror(errno));
errno = 0;
return EXIT_FAILURE;
}
}
int doPrint(char *path) {
if (strcmp(path, "stdin") == 0) {
fp = stdin;
} else {
if (checkFile(path) == 1) {
return EXIT_FAILURE;
} else {
fp = fopen(path, "r");
}
}
while ((c = fgetc(fp)) != EOF) {
putchar(c);
}
fclose(fp);
return EXIT_SUCCESS;
}
int main (int argc, char *argv[]) {
if (setFlags(argc, argv) == 1) {
fprintf(stderr, "The program has terminated with an error.\n"
"An invalid option was specified.\n");
return EXIT_FAILURE;
} else {
if ((argc - opt) == 0) {
doPrint("stdin");
} else {
for(int i = opt; i < argc; i++) {
doPrint(argv[i]);
}
}
}
}
I'm getting a really crazy bug, where my program outputs the error line in checkFile, before it finishes writing the contents of the file (always one chat before the end).
It's driving me insane, and no matter where I move that piece of code, it doesn't work as intended.
I'm sure the answer is probably trivial, but it has me stumped. I'd even thrown in sleeps and various other things just before output finished, and it would throw the error, THEN sleep, THEN print the final character.
Any help?
When using printf, stdout output is buffered by default. This means it can be interleaved with other output, often from stderr. stderr is unbuffered by default so that it's output is printed immediately as would normally be desired when an error occurs.
Interleaving can be fixed with judicious use of fflush or by turning off file buffering of stdout using setbuf. Be sure to read the man pages for setbuf as there are some caveats.
In this case, adding fflush(stdout) at the end of the doPrint function should fix the "problem".