I am new at c and I am writing a code that get a string from the user and compare it to a strings from the text file and my code is only working when I compare between two characters and when I compare between two strings it's not working If someone know how can I fix the problem it's will be verey helpful. the compare line is in the searchFile function. the text file is a csv file so insted compare the char to string I need to compare between what befor the , to the string_to_search. example for csv file at the end of the code
Example: string to search = 'c' work, string to search 'name' doesn't work
#include <stdio.h>
#define STR_LEN 100
int searchFile(char* string_to_search, char* path);
int main(int argc, char* argv[])
{
FILE* text_file = 0;
int found = 0, choice = 0;
char string_to_search[STR_LEN] = {0};
if (!(fopen(argv[1], "r") == NULL)) //check if file exists
{
do
{
printf("Please enter your choice:\n");
printf("1 - Search a term in the document.\n");
printf("2 - change a value in a specific place.\n");
printf("3 - copy a value from one place to another\n");
printf("4 - Exit\n");
scanf("%d", &choice);
getchar();
switch (choice)
{
case 1:
fgets(string_to_search, STR_LEN, stdin);
string_to_search[strcspn(string_to_search, "\n")] = 0;
found = searchFile(string_to_search, argv[1]); //found = where the string line
if (found != 0)
printf("Value was found in row %d\n", found);
else
printf("Value Wasn't Found\n");
}
}while(choice != 4);
}
else
{
printf("file does not exists\n");
}
getchar();
return 0;
}
int searchFile(char* string_to_search, char* path)
{
FILE* file = fopen(path, "r");
char ch = ' ';
int i = 0, len = 0, count = 1;
fseek(file, 0, SEEK_END);
len = ftell(file);
fseek(file, 0, SEEK_SET);
len = len - 2;
char* string = (char*)malloc(sizeof(char) * len);
do //copying the chars to a string
{
ch = fgetc(file);
string[i] = ch;
i++;
} while (ch != EOF);
fclose(file);
for (i = 0; i < len; i++)
{
if (string[i] == *string_to_search) //the compare
{
free(string);
return count;
}
if (string[i] == '\n')
{
count++;
}
}
free(string);
return 0;
}
Example for a CSV file:
roee,itay,3,4
5,6,7,8
a,b,c,d
e,f,g,h
==and strings withstrcmp()... period. (unless you roll your own loop to mimic whatstrcmp()does...)