I am trying to get name of the input, output, and data files from the array for further processing. However, I am getting a weird error or problem. So, my program is not reaching the for loop. It does not even print the statement before the for loop. However, I tried using the debugger and the program is correctly printing step by step. So, when I run it does not print and when I debug step by step it prints. That is Weird!
char *method;
method=malloc(25);
method=NULL;
char *dataFileName;
char *inputMethod;
inputMethod=malloc(25);
inputMethod=NULL;
char *inputFileName;
char *outputMethod;
outputMethod=malloc(25);
outputMethod=NULL;
char *outputFileName;
char *commandArray[]={"if=q.txt","of=output.txt"};
char**args=(char**) malloc(sizeof(char*)*256);
args=commandArray;
int i;
printf("Before second for");
for(i=0;i<2;i++)
{
printf("I am here");
if(*args[i]=='d')
{
method=strtok_r(args[i],"=",&dataFileName);
printf("The method given is %s",method);
printf("Data File Name is %s",dataFileName);
}
else if(*args[i]=='o')
{
outputMethod=strtok_r(args[i],"=",&outputFileName);
printf("The output method given is %s",outputMethod);
printf("output File Name is %s",outputFileName);
}
else
{
inputMethod=strtok_r(args[i],"=",&inputFileName);
printf("The input method given is %s",inputMethod);
printf("Input File Name is %s",inputFileName);
}
}
if(method==NULL)
{
dataFileName=malloc(256);
printf("Please Enter A File Name");
scanf("%255s",dataFileName);
printf("%s",dataFileName);
}
if((inputMethod==NULL)||(outputMethod==NULL) )
{
char* array[]={"stdin","stdout"};
if(inputMethod==NULL)
inputMethod=array[0];
if(outputMethod==NULL)
outputMethod=array[1];
}
I am developing using Netbeans in C. The above code is written inside main. Thanks!
i intentionally left the previous answer because understanding memory allocation is trivial in programming in c specially. and as i see you have a big issue with that.
but still you have issue in nearly every thing. in my actual answer, i will try to simplify you how to use strtok, to split string and parse it. i guess this is the second main problem with your code.
the code :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void){
char commandArray[][256]={
"if=q.txt",
"of=output.txt"
};
char infile[256], outfile[256];
for(int i=0; i<2;i++){
char *ptr,*cmd;
cmd=commandArray[i];
ptr=NULL;
printf("parsing command '%s'\n",cmd);
cmd=strtok(cmd,"=");
ptr=strtok(NULL,"=");
if(!cmd){
printf("Error parsing the string '%s'\n",commandArray[i]);
exit(1);
}
if (strcmp(cmd,"if")==0){
strcpy(infile,ptr);
}
else if (strcmp(cmd,"of")==0){
strcpy(outfile,ptr);
}
else{
printf("unknow token '%s'\n",cmd);
exit(1);
}
}
printf(
"\n\n"
"input file: '%s'\n"
"output file: '%s'\n"
"\n\n",
infile,outfile);
return 0;
}
the main problem is this:
char *method;
method=malloc(25);//allocating space for 25 char
method=NULL; // throwing up the allocation without freeing it;
// now the allocation is lost
// now method is useless (it is null)
Related
My program it's pretty big, so I'll highlight the main problem and add some details about it.
First part of my code:
int myPipe[2]; //A global variable, so I don't have to pass it to future functions
int main(int argc, char *args[])
{
mode_t pUmask = umask(0000); //Obsolete variable to my problem
errno = 0; //Obsolete variable to my problem
char pattern[2500] = "Test1"; //Obsolete variable to my problem
int p = 0; //DEFAULT NUMBER OF PROCESSES
int deep = 0; //Obsolete variable to my problem
int n = 1; //Obsolete variable to my problem
if(pipe(myPipe))
{
perror("Pipe Error: ");
exit(-1);
}
if( (write(myPipe[1], &p, (sizeof(int)*3))) == -1) //First write works
{
perror("write: ");
exit(-1);
}
//Then a bunch of code releated to file reading
}
Second part:
{
//in another function
//The part where I create fileName
char* fileName = calloc(strlen(fileData->d_name)+4, sizeof(char));
strcpy(fileName, fileData->d_name);
}
Third part:
//in another another function
if(S_ISREG(data.st_mode))
{
printf("\tfileName: %s\n", fileName); //Regular print of the right fileName
printf("\t\tOh boy! It's a regular.\n");
printf("\tfileName: %s\n", fileName); //Regular print of the right fileName
if((read(myPipe[0], &p, (sizeof(int)*3))) == -1) //First time I read
{
perror("\t\t read: ");
exit(-1);
}
printf("fileName: %s", fileName); //SEGMENTATION FAULT
There is a bunch of code in between, but it doesn't affect the fileName at all (in fact, up until the "read", fileName was printed flawlessly), and after it a SEGMENTATION FAULT happens.
At one point by changing the printfs locations I was able to get the fileName AFTER the read, which was basically the fileName value("File1") followed by the p integer value(0), which created the new corrupted fileName("File10").
So what's happening? I reserved the space for fileName, I passed the fileName pointer to the following functions up to that read, and supposedly the fd should have it's own adress space as well. HELP.
P.s. if you need more info, I'm willing to give it to you, even the full code, but it's REALLY complicated, and I think I gave you enough proof that fileName doesn't get corrupted at all until the read part, THANK YOU.
P.p.s.
I never close either of the "MyPipe" extremes, since I have to use them multiple times, I wanted to close them at the end of the program.
The statements that write and read the pipe are causing undefined behavior. p is declared:
int p;
But when you write and read it through the pipe, you use sizeof(int)*3, so you're accessing outside the object.
Change those statements to use just sizeof p.
Okay so overall im trying to complete a basic CLI C program which will complete functions such as clear, quit, cd, ls, help (bring up the unix man) etc.. i altered my code and so far i have this, im getting segmination error when trying to execute the cd command part of the program, (im very new to c btw);
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
int main (int argc, char *argv[])
{
char input[] = " ";
char *argument;
while(strcmp(input, "quit")!= 0)
{
printf("$");
scanf ("%s", input);
if(strcmp(input,"clear") == 0)
{
printf("\e[1;1H\e[2J");
}
else if(strcmp(argv[1],"cd") == 0)
{
if(chdir(argv[2]) == -1)
{
printf("\n directory does not exists");
}
}
else if(strcmp(input, "echo") == 0)
{
char str[50];
scanf("%[^\n]+", str);
printf(" %s", str);
}
}
}
input is declared as a ' ' (space) character. It will never match 'cd'.
This is probably more along the lines of what you want to achieve, where the first parameter is the command (cd), and the second will be the directory:
int main (int argc, char *argv[])
{
char *argument;
if(strcmp(argv[1],"cd") == 0)
{
if(chdir(argv[2]) == -1)
{
printf("\n directory does not exists");
}
}
Edit Also please note that there is no need for the else satement. If chdir does not return an error, it will change the directory, thus no need to call it again in an else.
Additionally, another tip for using system calls in general, it would be of great help if you print the error number returned by the system upon a failure in system call. This will make things easier when things start going wrong. To do this simply include <errno.h>' and modify the printf to printerrno` which gives specific details about the error:
printf("Chdir error: %d", errno);
For instance chdir() does not only return an error when the directory does not exist, but also for example if you do not have permissions to view the contents of the directory. See the man page for a list of possible errors.
To implement your own shell, you need to take input directly from stdin, not from command-line arguments (argv) from another shell. The basic pattern is like this:
Read input
Execute command
Print results
Loop back to step 1
I'm learning to create multi-file programs for one of my classes. Ultimately I need to implement a stack and do some stuff with the stack. Before I began implementing the stack I wanted to make sure my files were all linked together properly with a header file. For some reason when the user inputs "pop" or "print" the conditional statement is not triggered and the method in stack.c is not called. I've been looking at this for awhile and haven't gotten anywhere. Thank you for the help
MAIN.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "stack.h"
void pop(char list[]);
void print(char list[]);
void push(char list[]);
int main(void)
{
char input[5];
char test[5];
while( strcmp("exit",input) != 0)
{
printf("Please enter a command. \n");
fgets(input,sizeof(input),stdin);
if(strcmp("pop",input)==0)
{
pop(test);
}
else if(strcmp("push",input)==0)
{
push(test);
}
else if (strcmp("print", input)==0)
{
print(test);
}
}
return 0;
}
STACK.c
#include <stdio.h>
#include <stdlib.h>
#include "stack.h"
void pop(char list [])
{
printf("This is in the stack file in pop\n");
}
void push(char list [])
{
printf("This is in the stack file in push\n");
}
void print(char list[])
{
printf("This is in the stack file in print\n");
}
Console Output
Please enter a command.
push
This is in the stack file in push
Please enter a command.
Please enter a command.
pop
Please enter a command.
print
Please enter a command.
Please enter a command.
exit
I will suggest use of strstr() instead of strcmp(). If you use strstr() then there is no need to mention '\n' in the string to be searched.
The strstr() function finds the first occurrence of the substring needle in the string haystack.
For better understanding you can visit,
http://man7.org/linux/man-pages/man3/strstr.3.html
Code will look like,
while( strstr(input,"exit") == NULL)
{
printf("Please enter a command. \n");
memset(input,0,sizeof(input));
fgets(input,sizeof(input),stdin);
if(strstr(input,"pop"))
{
printf("pop\n");
}
else if(strstr(input,"push"))
{
printf("push\n");
}
else if (strstr(input,"print"))
{
printf("print\n");
}
}
I agree with #Govind Parmar that 5 bytes are not sufficient for input buffer. You need to declare input buffer with 7 bytes.
Three things:
The line read by fgets() will include \n at the end. Test for strcmp("word\n", input)==0.
5 is not sufficient size for input since you need to be testing for newlines ("push\n\0" is 6 bytes; "print\n\0" is 7 bytes)
You test for strcmp("exit", input) without input being initialized. This is undefined behavior. Set input to be all-zeroes before beginning your loop.
I was asked to make a C program that act as a 'price lookup' where a user enter a product name and the program will print it's name and price which is stored in a file. If the item is not present in the file, the program will let the user know. The program will keep looping as long as the user wants to search. I did the coding using Dev C++, however after i run the code, the program got stuck after a few loops, and it's random. Could you guys detect any problem with my coding, or is it just the problem with Dev C++? I include my code below. Your help is greatly appreciated.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<conio.h>
#include<ctype.h>
int main()
{
FILE *items;
char *mode="r";
char pName[50];
float pPrice;
char p1Name[50];
int value=0;
char respond='Y';
char s[50];
items=fopen("Product_Name_Price.txt", mode);
if(items==NULL)
{
fprintf(stderr, "Can't open file Product_Name_Price.txt!\n");
exit(1);
}
printf("File has been successfully opened\n");
do
{
printf("Enter the name of the product you wish to look for\n");
scanf("%s", &p1Name);
while(strcmp(p1Name, pName) !=0)
{
fscanf(items,"%s %f", pName, &pPrice);
//printf("%s\t%.2f\n", pName, pPrice);
//value=strcmp(p1Name, pName);
if(strcmp(p1Name, pName) == 0)
{
printf("%s\t%.2f\n", pName, pPrice);
}
}
/*
else
{
printf("No data in system\n");
}
*/
printf("Do you wish to look up for more item? (Y/N)\n");
scanf("%s", &respond);
}while(respond=='Y'|| respond=='y');
printf("This program is closing\n");
fclose(items);
}
Your program has undefined behaviour because your scanf("%s", &response) reads into response as if it were an array of sufficient size for the string being read — that size is at least 2 (including null terminator), but response is just one character. You blew up your stack and corrupted memory and then all bets are off.
You could write scanf("%c", &response) instead to actually read a single character, though you'd be better off switching to modern, safer tools if you're writing a C++ program.
I'm currently trying to use a struct "test", to print an array of 10 random things the user inputs. The program compiles, and runs, however after I enter the final 10th item, the .txt file only contains the first element I've entered.I've tried moving the area of which the fprintf function is called, but my attempt at that was to no avail. Any input on this would be much appreciated.
Continues to only print the first element (i.e what I type first)
#include <stdio.h>
#include <ncurses.h>
//EDIT NEW CODE UPDATED, BUT IT STILL ONLY PRINTS THE FIRST ELEMENT\\
typedef struct test
{
char test[10];
}test;
int main(void)
{
initscr();
cbreak();
noecho();
testFunction();
}
int testFunction()
{
int i;
test inputString[10];
FILE *f = fopen("file.txt", "w");
for(i=0;i<10;i++)
{
mvprintw(50,50,"Please enter a 10 things");
getstr(inputString[i].test);
fprintf(f, "%s\n", inputString[i].test);
}
fclose(f);
}
You're closing your file inside the loop, and not opening it again.
Move the fclose() call to outside your loop.
By the way, you don't need the while loop.