While I am aware there are libraries for config file parsing I have tried to write my own implementation. The problem is that I can find the config option but comparing the string before the delimeter failes when I try to compare it with the thing I am searching for. I need to comare it with the thing I am searching for becasue my program allows things like Test2 and Test3 because it cannot check if there are characters before or after the word Test. The compare allways failes and I cannot figure out why.
Here is my code:
Main.c
#include <stdio.h>
#include <stdlib.h>
void Parser(char *CONFIG_FILE, int *P_VALUE, char *STRING_TO_LOOK_FOR);
int main(){
int VALUE;
Parser("config.txt", &VALUE, "Test");
printf("%d \n", VALUE);
}
Parser.c:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void Parser(char *CONFIG_FILE, int *P_VALUE, char *STRING_TO_LOOK_FOR){
FILE *FP=fopen(CONFIG_FILE,"a+");
char TMP[256]={0x0};
int i = 1;
while(FP!=NULL && fgets(TMP, sizeof(TMP), FP)!=NULL){ //Loop through every line
i=i+1; //Increment the line number
if (strstr(TMP, STRING_TO_LOOK_FOR)){ //Is the term im looking for in this line
char *NAME_OF_CONFIG_STR = strtok(TMP, "= "); //look for delimiter
char *STRVALUE = strtok(NULL, "= "); //Get everything past the delimiter
char *P_PTR;
char *pos;
if ((pos=strchr(NAME_OF_CONFIG_STR, '\n')) != NULL){ //attempt remove \n doesn't work
*pos = '\0';
}
if(strcmp(STRING_TO_LOOK_FOR, NAME_OF_CONFIG_STR) == 0){ //try to check the two are the same
*P_VALUE = strtol(STRVALUE, &P_PTR, 10); //Returns an integer to main of the value
}
}
}
if(FP != NULL){
fclose(FP);
}
}
config.txt:
Test= 1234
Test2= 5678
Test3= 9012
Thanks to BLUEPIXY and the demo they created this problem has been solved. The issue was in the gcc comiler options I had forgotten -std=99 somehow this caused the program to behave correctly.
Related
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
int main(int args, char* argv[])
{
const int CBUFF = 1024;
char input[CBUFF];
char wkdir[CBUFF];
char* command;
printf("Welcome to MyShell...\n");
while(1)
{
getcwd(wkdir, CBUFF);
printf("%s ? ", wkdir);
fgets(input, CBUFF, stdin);
command = strtok(input, " ");
if(strcmp(command, "cd") == 0)
{
char* path;
path = strtok(NULL, " ");
if(chdir(path) != 0)
{
printf("ERROR: COULD NOT CHANGE DIRECTORY TO SPECIFIED PATH");
}
}
if(strcmp(command, "exit") == 0) break;
}
return 0;
}
I am running into an issue creating a very simple command shell in C. The input is only being read the way I want it too when I add a space after my directive. I know that it has something to do with my improper use of the strtok() function but am not able to figure out what I am doing wrong. I have read the documentation of <string.h> and am turning up blank.
Behavior I want:
Directive "exit" to exit from program.
Current behavior:
Must add space after directive to get it to parse correctly ie. "exit " or "cd " is entered.
You left the trailing newline in the buffer. Get rid of it.
char *got = fgets(input, CBUFF, stdin);
if (!got) return ; /* EOF -- treat like exit */
size_t gotlen = strlen(got);
if (got[gotlen] == '\n') got[gotlen] = 0;
I am trying to make a function that reads a text file which contains data and assign it to a variable. However some lines start with $ which need to be ignored. For example:
$ Monday test results
10 12
$ Tuesday test results
4
This is what I have so far which just prints out:
10 12
4
The code that does this is:
#include <stdio.h>
#include <stdlib.h>
void read_data(){
FILE* f;
if (f = fopen("testdata.txt", "r")) {
char line[100];
while (!feof(f)) {
fgets(line, 100, f);
if (line[0] == '$') {
continue;
} else{
puts(line);
}
}
} else {
exit(1);
}
fclose(f);
}
void main(){
read_data();
return 0;
}
I have tried fgetc and have googled extensively but am still stuck ;(
**Edits
Added #include and main
What I am asking is how to assign like a = 10, b = 12, c = 4. Had troubles since using fgets is for lines. Tried fgetc but it would only ignore the actual $ sign not the whole line that the $ is on
C string.h library function - strtok()
char *strtok(char *str, const char *delim)
str − The contents of this string are modified and broken into smaller strings (tokens).
delim − This is the C string containing the delimiters. These may vary from one call to another.
This function returns a pointer to the first token found in the string. A null pointer is returned if there are no tokens left to retrieve.
Copied from: https://www.tutorialspoint.com/c_standard_library/c_function_strtok.htm
#include <string.h>
#include <stdio.h>
int main () {
char str[80] = "This is - www.tutorialspoint.com - website";
const char s[2] = "-";
char *token;
/* get the first token */
token = strtok(str, s);
/* walk through other tokens */
while( token != NULL ) {
printf( " %s\n", token );
token = strtok(NULL, s);
}
return(0);
}
Output:
This is
www.tutorialspoint.com
website
I want to make a program that imitates the use of cd in UNIX. Obviously the best option is chdir. However when the user types cd /home I get Segmentation fault. When I use gdb, it prints:
Program received signal SIGSEGV, Segmentation fault. __rawmemchr_avx2 () at ../sysdeps/x86_64/multiarch/memchr-avx2.S:61
61 ../sysdeps/x86_64/multiarch/memchr-avx2.S: The file of directory does not exist.
The code looks like this:
void cd(char buff[]){
if(chdir(buff)==-1){
printf("Problem with directory\n");
}
}
int main(int argc, char *argv[]){
char* token;
char buffer[256];
printf("Welcome user\n");
sscanf("%s",buffer);
token=strtok(buff," ");
if(strcmp(token,"cd")==0||strcmp(token,"cd\n")==0){
cd(strtok(NULL," ");
}
return 0;
}
Than you for your time.
You have made a few syntactic and logical mistakes inside the provided code, like for example buff instead of buffer in main()and sscanf instead of scanf for giving the input string.
Also, you wrote cd(strtok(NULL," "); but a closing brace is missing for this statement to compile: cd(strtok(NULL," "));.
I've corrected the code and the output file runs fine on my platform - with GCC on Ubuntu GNU/Linux.
Here is the corrected code:
#include <stdio.h>
#include <string.h>
#include <unistd.h>
void cd(char buff[]){
if(chdir(buff)==-1){
printf("Problem with directory\n");
}
}
int main(int argc, char *argv[]){
char* token;
char buffer[256];
printf("Welcome user\n");
scanf("%s",buffer);
token=strtok(buffer," ");
if(strcmp(token,"cd")==0||strcmp(token,"cd\n")==0){
cd(strtok(NULL," "));
}
return 0;
}
Try it with this.
This code has several problems:
1) even if sscanf is swapped for scanf, it does not do what you probably expect it to (read the whole line inserted by the user). scanf with %s will read up to the first whitespace. So, your buffer will actually contain cd\0 instead of cd /home\0 like you expect it to. Use fgets instead.
2) You must check that strtok does not return a NULL pointer. This is what is currently causing your segfault.
Something like this:
void cd(char buff[]) {
if(chdir(buff) == -1) {
printf("Problem with directory\n");
}
}
int main(int argc, char *argv[]){
char* token;
char buffer[256];
printf("Welcome user\n");
// reads the whole line into buffer
fgets(buffer, 256, stdin);
token = strtok(buffer, " ");
if (strcmp(token, "cd") == 0){
token = strtok(NULL," ");
// we must check if there are any tokens left
if (token != NULL) {
// we must remove the trailing newline character that is included by fgets
cd(strtok(token, "\n"));
}
}
return 0;
}
I have an document with some telephone number and andresses.
I now try to copy the numbers in one part of a struct and the adress into another.
At the moment I was just able to get the data of the document but I can't put it in my struct please help me
C Code
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
struct telefon{
char nummer[16];
char adresse[128];
};
typedef struct telefon TELEFON;
void main()
{
TELEFON tel;
char buffer[256];
FILE *fp;
int i = 0;
int countSemi = 0;
fp = fopen("Telefondatei.txt", "r");
if(fp == NULL)
{
printf("Datei konnte nicht geoeffnet werden.\n");
}
else{
while(fgets(buffer,1000,fp) != 0){
//printf("%s\n",buffer);
while(buffer != 0){
i++;
if(buffer[i] == ';'){
countSemi++;
}
while(countSemi <= 7){
strcpy(tel.adresse,buffer);
printf("%s\n %d \n",tel.adresse,countSemi);
}
}
}
}
}
Example for the data in my .txt document
"Firma";"";"Auto GmbH";"gasse 3";"5000";"Mon";"";"0456";"45652"
"Firma";"";"ADAC";"";"50000";"Mon";"";"2156";"545218"
You will need to use strtok additionally. See this example. However, please note this example assumes the data is written in fixed format (and it will not work if data comes in other format - you might want to modify this for your needs, this is just illustration):
Assumed data format for each line:
Address;telephoneNumber;
#include <string.h>
..
char * value;
while(fgets(buffer,256,fp) != 0)
{
value = strtok(buffer, ";"); // get address
strcpy(tel.adresse, value);
value = strtok(NULL, ";"); // get number
strcpy(tel.nummer, value);
}
Also this:
while(buffer != 0)
in your code doesn't make sense. Hardly buffer will be 0. It is array and value of buffer will always be memory address where that array starts. You can't assign to buffer.
Here is another post about using strtok.
To get your data use : fscanf(fp, "%s %s %s %d", str1, str2, str3, &number);
or you can use getc to get one character but u need to test the EOF
I already asked on question earlier about the string function strstr, and it just turned out that I had made a stupid mistake. Now again i'm getting unexpected results and can't understand why this is. The code i've written is just a simple test code so that I can understand it better, which takes a text file with a list of 11 words and i'm trying to find where the first word is found within the rest of the words. All i've done is move the text document words into a 2D array of strings, and picked a few out that I know should return a correct value but are instead returning NULL. The first use of strstr returns the correct value but the last 3, which I know include the word chant inside of them, return NULL. If again this is just a stupid mistake I have made I apologize, but any help here on understanding this string function would be great.
The text file goes is formatted like this:
chant
enchant
enchanted
hello
enchanter
enchanting
house
enchantment
enchantress
truck
enchants
And the Code i've written is:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) {
FILE* file1;
char **array;
int i;
char string[12];
char *ptr;
array=(char **)malloc(11*sizeof(char*));
for (i=0;i<11;i++) {
array[i]=(char *)malloc(12*sizeof(char));
}
file1=fopen(argv[1],"r");
for (i=0;i<11;i++) {
fgets(string,12,file1);
strcpy(array[i],string);
}
ptr=strstr(array[1],array[0]);
printf("\nThe two strings chant and %s yield %s",array[1],ptr);
ptr=strstr(array[2],array[0]);
printf("\nThe two strings chant and %s yield %s",array[2],ptr);
ptr=strstr(array[4],array[0]);
printf("\nThe two strings chant and %s yield %s",array[4],ptr);
ptr=strstr(array[5],array[0]);
printf("\nThe two strings chant and %s yields %s",array[5],ptr);
return 0;
}
Get rid of the trailing \n after fgets().
for (i=0;i<11;i++) {
fgets(string, sizeof string, file1);
size_t len = strlen(string);
if (len > 0 && string[len-1] == '\n') string[--len] = '\0';
strcpy(array[i], string);
}
char *chomp(char *str){
char *p = strchr(str, '\n');
if(p)
*p = '\0';
return str;
}
...
strcpy(array[i], chomp(string));