I'm doing a school project in C using xcode. The task is to create a command line application that checks if and how many times a word appears in a text file. So far I've just created the first step of the code, I have set the first argue argument to "hej" even though Im not using the word yet, and because of the first filename is not entered and therefore NULL, I have set it to be an existing file called "hej.txt", in order to test my code as I go.
This bit worked before:
#include "stdio.h"
#include "string.h"
struct fileSearch
{
char *inFile;
char *outFile;
char *searchWord;
};
int main(int argc, char *argv[])
{
int index = 0;
struct fileSearch f;
f.searchWord = argv[1];
FILE *searchFile;
//For-loop to assign filenames
for(index = 0; index < argc ; ++index)
{
if((strcmp(argv[index], "-i") == 0) && argv[index] != NULL && strcmp(argv[index + 1], "-o") != 0)
{
f.inFile = argv[index + 1];
}
if((strcmp(argv[index], "-o") == 0) && argv[index] != NULL && strcmp(argv[index + 1], "-c") != 0)
{
f.outFile = argv[index + 1];
}
}
if (f.searchWord == NULL)
{
printf("You didnt enter a search word");
}
if (f.inFile == NULL)
{
f.inFile = "hej.txt";
}
if (f.outFile == NULL)
{
f.outFile = "stdout.txt";
}
printf("%s & %s & %s", f.searchWord, f.inFile, f.outFile);
return 0;
}
It then printed out the search word, the input filename and the output filename.
Then I added the next step of the code where it would open the text file "hej.txt" and then read the strings and print them.
#include "stdio.h"
#include "string.h"
struct fileSearch
{
char *inFile;
char *outFile;
char *searchWord;
};
int main(int argc, char *argv[])
{
int index = 0;
struct fileSearch f;
f.searchWord = argv[1];
FILE *searchFile;
//For-loop to assign filenames
for(index = 0; index < argc ; ++index)
{
if((strcmp(argv[index], "-i") == 0) && argv[index] != NULL && strcmp(argv[index + 1], "-o") != 0)
{
f.inFile = argv[index + 1];
}
if((strcmp(argv[index], "-o") == 0) && argv[index] != NULL && strcmp(argv[index + 1], "-c") != 0)
{
f.outFile = argv[index + 1];
}
}
if (f.searchWord == NULL)
{
printf("You didnt enter a search word");
}
if (f.inFile == NULL)
{
f.inFile = "hej.txt";
}
if (f.outFile == NULL)
{
f.outFile = "stdout.txt";
}
printf("%s & %s & %s", f.searchWord, f.inFile, f.outFile);
//Open file and read
char str[60];
searchFile = fopen(f.inFile, "r");
if(searchFile = fopen(f.inFile, "r") == NULL)
{
printf("Error: There is no file with that name.");
return -1;
}
if(searchFile == NULL)
{
printf("The file is empty");
return -1;
}
while(fgets(str, 60, searchFile) != NULL)
{
puts(str);
}
fclose(searchFile);
return 0;
}
However now it builds the code successfully but when I try to run it, I get this error message:
"error: executable doesn't exist: '/Users/Slattegard/Library/Developer/Xcode/DerivedData/Coursework-chwsqczjjgxcyegnxgysiaigslvq/Build/Products/Debug/Coursework'
error: failed to launch '/Users/Slattegard/Library/Developer/Xcode/DerivedData/Coursework-chwsqczjjgxcyegnxgysiaigslvq/Build/Products/Debug/Coursework'"
and the Issue Navigator gives me this message:
"Check dependencies
warning: no rule to process file '/Users/Slattegard/Documents/Coursework/Coursework/Find.c' of type sourcecode.c for architecture x86_64"
Anyone know where I am going wrong?
Related
I wrote a program that implements the grep command. I tried to search by several words. I use the -e WORD option to search by word in the target file, so if the option is present several times in the command line you can search for more words grep will display any line that contains at least one searched word.
I would like you to criticize the implementation of this option (-e WORD). What possible problems may arise?
Something tells me that I could have implemented it even better
I think the treatment of this grep option could have been better written
code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char** argv){
if(argc < 3) {
printf("Usages:\n1: ./grep.o <word> <file>\n2: ./grep.o -e <word> [-e <word>...] <file>\n");
return 1;
}
else {
FILE* fp;
char* line = NULL;
size_t len = 0;
ssize_t read;
int i;
fp = fopen(argv[argc - 1], "r");
if(fp == NULL) {
printf("File doesn't exist or cannot be read!\n");
return 1;
}
if(argc == 3) {
while((read = getline(&line, &len, fp)) != -1) {
if(strstr(line, argv[1]) != NULL)
printf("%s", line);
}
}
else {
for(i = 1; i < argc - 2; i += 2) {
if(strcmp(argv[i],"-e") != 0) {
printf("The option must be \"-e\"!\n");
fclose(fp);
return 1;
}
}
if(i + 1 == argc - 1) {
if(strcmp(argv[i],"-e") != 0) {
printf("The option must be \"-e\"!\n");
}
else {
printf("The option must have a word after it!\n");
}
fclose(fp);
return 1;
}
while((read = getline(&line, &len, fp)) != -1) {
for(i = 1; i < argc - 2; i += 2) {
if(strstr(line, argv[i + 1]) != NULL) {
printf("%s", line);
break;
}
}
}
fclose(fp);
if(line)
free(line);
}
return 0;
}
}
So I have this code which I was working on. The goal is to search for a string in a file and when that string is found it would return the corresponding values in that section of the file. So this is the file in question that is being searched:
So if it finds "AJ" then it would return all the values right up to "22550" and if it finds "TS" then it prints everything after "TS" and after "60500." This is my code in question:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char *name;
char *code;
int grpsize;
char route;
char *package;
//float fee;
float tcost;
float fcost;
} bookingrecord;
int main() {
FILE *fptr;
bookingrecord bookingrec;
char book_code[5];
printf("\n Please enter the code that corressponds to your record: ");
scanf("%s", book_code);
fptr = fopen("bookingdata", "r");
if (fptr == NULL) {
printf ("\nSorry we didn't find your file.");
exit (1);
}
ssize_t read;
char * line = NULL;
size_t len = 0;
int count = 0;
int found = 0;
while ((read = getline(&line, &len, fptr)) != -1) {
if (count == 0) {
bookingrec.code = line;
//printf("%s %s",bookingrec.code,book_code);
if (strcmp(bookingrec.code, book_code) == 0) {
found = 1;
}
} else if (count == 1 && found == 1) {
bookingrec.grpsize = line;
} else if (count == 2 && found == 1) {
bookingrec.route = line;
} else if (count == 3 && found == 1) {
bookingrec.fcost = strtof(line, NULL);
} else if (count == 4 && found == 1) {
bookingrec.name = line;
} else if (count == 5 && found == 1) {
bookingrec.package = line;
} else if (count == 6 && found == 1) {
bookingrec.tcost = strtof(line, NULL);
}
count = count + 1;
if(strlen(line) == 0) {
count = 0;
}
}
if (found == 1) {
printf("\n We have found your file");
printf("\n %s", bookingrec.code);
printf("\n %s", bookingrec.name);
printf("\n %d", bookingrec.grpsize);
printf("\n %s", bookingrec.route);
printf("\n %c", bookingrec.package);
printf("\n %.2f", bookingrec.tcost);
printf("\n %.2f", bookingrec.fcost);
}
fclose(fptr);
return 0;
}
The problem is that it only gives me this as the result:
So it finds the file okay but nothing happens so I uncomment a printf which I added to troubleshoot a bit right above my strcmp and get this when I enter for eg. "AJ":
I try another of the two character string. "SH" in this case and get this:
So it seems as if it is accepting any of the codes but prints the first line twice? But also discards everything else. I am a bit stumped as to what is happening. Any ideas?
Update:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char *name;
char *code;
int grpsize;
char *route;
char *package;
//float fee;
float tcost;
float fcost;
} bookingrecord;
int main() {
FILE *fptr;
bookingrecord bookingrec;
char book_code[5];
printf("\n Please enter the code that corressponds to your record: ");
scanf("%s", book_code);
fptr = fopen("bookingdata", "r");
if (fptr == NULL) {
printf ("\nSorry we didn't find your file.");
exit (1);
}
ssize_t read;
char * line = NULL;
size_t len = 0;
int count = 0;
int found = 0;
while ((read = getline(&line, &len, fptr)) != -1) {
line[strcspn(line, "\r\n")] = 0; //trims getLine
//printf("line is %s, count is %d \n", line, count);//debugging
if (count == 0) {
bookingrec.code = strdup(line);
if (strcmp(bookingrec.code, book_code) == 0) {
found = 1;
}
} else if (count == 1 && found == 1) {
char *tmp;
bookingrec.grpsize = strtol(strdup(line), NULL, 10);
} else if (count == 2 && found == 1) {
bookingrec.route = strdup(line);
} else if (count == 3 && found == 1) {
bookingrec.fcost = strtof(strdup(line), NULL);
} else if (count == 4 && found == 1) {
bookingrec.name = strdup(line);
} else if (count == 5 && found == 1) {
bookingrec.package = strdup(line);
} else if (count == 6 && found == 1) {
bookingrec.tcost = strtof(strdup(line), NULL);
}
count = count + 1;
if (found == 1 && count == 7){
break;
}
if(strlen(line) == 0) {
count = 0;
}
}
if (found == 1) {
printf("\n We have found your file");
printf("\n %s", bookingrec.code);
printf("\n %s", bookingrec.name);
printf("\n %d", bookingrec.grpsize);
printf("\n %s", bookingrec.route);
printf("\n %s", bookingrec.package);
printf("\n %.2f", bookingrec.tcost);
printf("\n %.2f", bookingrec.fcost);
}
fclose(fptr);
return 0;
}
Updated screens after edits:
Program should read list of filenames, open these files and put their handles in the array of structure, then read strings and print consecutive lines of strings to smallest files by using handles contained in array of structures.
My program puts data from all lines to only one file which is initially the smallest which is false because it should the one which is smallest with every time it prints data into the file. This is my program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <math.h>
struct file_t
{
FILE* f;
int size;
}t[5];
void close_file(struct file_t* f) {
if (f == NULL || f->f == NULL) {
}
else {
fclose(f->f);
}
}
int open_file(struct file_t* f, const char* filename) {
if (f == NULL || filename == NULL) {
return 1;
}
FILE* fp;
fp = fopen(filename, "ab");
if (fp == NULL) {
return 2;
}
long int res = ftell(fp);
fclose(fp);
f->size = res;
f->f = fopen(filename, "ab+");
if (fp == NULL) {
return 2;
}
return 0;
}
struct file_t* find_min(const struct file_t* files, int size) {
if (files == NULL || size <= 0) {
return NULL;
}
int x = (files + 0)->size, i = 0, index = 0;
for (i = 0; i < size; i++) {
if ((files + i)->size <= x) {
x = (files + i)->size;
index = i;
}
}
return (struct file_t*)(files + index);
}
int main() {
puts("Input files' names:");
char tab[100];
int num = 0;
while(1==1){
if(fgets(tab, 100, stdin)==NULL||*tab=='\n'){
if (num == 0) {
printf("Couldn't open file");
return 4;
}
break;
}
int index=strlen(tab);
*(tab+index-1)='\x0';
if (strlen(tab) > 30) {
*(tab + 30) = '\x0';
}
if (open_file((t + num), tab) > 0) {
}
else {
num++;
}
}
if (num == 0) {
printf("Couldn't open file");
return 4;
}
char str[1000];
printf("Input text:");
*str = '\x0';
while (fgets(str, 1000, stdin)==NULL||*str!='\n') {
int index=strlen(str);
*(str+index-1)='\x0';
struct file_t* p = find_min(t, num);
fwrite(str, sizeof(char), strlen(str), p->f);
}
for (int i = 0; i < num; i++) {
close_file(t + i);
}
printf("File saved");
return 0;
}
There are some critical bugs that you need to resolve.
fseek(stdin, 0, SEEK_END) -- fseek normally only work on a disk file, or something reasonably similar. Please refer to this link Using fseek with a file pointer that points to stdin
As a matter of fact even fflush() won't work. fflush is something that is designed for flushing output streams, and its behavior with input streams is implementation-dependent. Please refer to this link for more details stdinflush
scanf("%[^\n]s", tab)
If you are using this in a loop or multiple times, only the first read will succeed. The reason being, the \n character is left out from the previous input, and as said earlier fflush() might not be successful in removing that \n. The further calls to scanf() will simply return without reading anything.
'\0x' If you are intending to use this as string terminator then this is not it. It is a multi-character constant with an integer value 120. Below is a vague test run
Code
#include <stdio.h>
int main()
{
if ('\0' == '\0x' )
printf("both are same\n");
printf("%d",'\0x');
}
Compilation Warnings
test.c: In function ‘main’:
test.c:5:14: warning: multi-character character constant [-Wmultichar]
5 | if ('\0' == '\0x' )
| ^~~~~
test.c:8:14: warning: multi-character character constant [-Wmultichar]
8 | printf("%d",'\0x');
| ^~~~~
Output
120
fseek(fp, 0, SEEK_END); ftell(fp); -- This should not be used to determine the file sizes. The behavior of the fseek() with SEEK_END is undetermined in the case of binary files. Please refer to this link Do not use fseek() and ftell() to compute the size of a regular file
Some Logic Errors
1) You should compute the file size every time in find_min() as it gets changed whenever you write data to the file.
2) fwrite()won't actually dump the data to file immediately. you need to call fflush().
After resolving the above issues, this is the modified code.
Code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <math.h>
#include <sys/stat.h>
struct file_t
{
FILE* f;
int size;
}t[5];
void close_file(struct file_t* f) {
if (f == NULL || f->f == NULL) {
}
else {
fclose(f->f);
}
}
int open_file(struct file_t* f, const char* filename) {
if (f == NULL || filename == NULL) {
return 1;
}
f->f = fopen(filename, "a");
if (f->f == NULL)
return 2;
struct stat statbuf;
fstat(fileno(f->f), &statbuf);
f->size = statbuf.st_size;
return 0;
}
struct file_t* find_min(const struct file_t* files, int size) {
if (files == NULL || size <= 0) {
return NULL;
}
struct stat statbuf;
fstat(fileno(files->f), &statbuf);
int x = statbuf.st_size, i = 0, index = 0;
for (i = 0; i < size; i++) {
fstat(fileno((files+i)->f), &statbuf);
if (statbuf.st_size < x) {
x = statbuf.st_size;
index = i;
}
}
return (struct file_t*)(files + index);
}
int main() {
puts("Input files' names:");
char tab[100];
int num = 0;
while(1){
int c;
while (1) {
c = getc(stdin);
if (c == EOF || c == ' ')
goto user_input;
if(c != '\n')
break;
}
tab[0] = c;
if (scanf("%[^\n]s", tab+1) == EOF)
break;
if (*tab == '\0') {
if (num == 0) {
printf("Couldn't open file");
return 4;
}
break;
}
if (strlen(tab) > 30) {
*(tab + 30) = '\0';
}
if (open_file((t + num), tab) > 0) {
}
else {
num++;
}
*tab = '\0';
}
user_input:
if (num == 0) {
printf("Couldn't open file");
return 4;
}
fflush(stdin);
char str[1000];
printf("Input text:\n");
*str = '\0';
while(1) {
int c;
while(1) {
c = getc(stdin);
if (c == EOF)
goto main_exit;
if (c != '\n')
break;
}
str[0] = c;
if (scanf("%[^\n]s", str+1) == EOF)
break;
struct file_t* p = find_min(t, num);
fwrite(str, sizeof(char), strlen(str), p->f);
fflush(p->f);
}
main_exit:
for (int i = 0; i < num; i++) {
close_file(t + i);
}
printf("File saved");
return 0;
}
Terminal Session
$ ./a.out
Input files' names:
test file1.txt
test file2.txt
' '(NOTE: Space character inputted before pressing enter.)
Input text:
this is
stackoverflow
File saved
test file1.txt
this is
test file2.txt
stackoverflow
Note for breaking from the first loop (Files input). You need to enter space and then press enter (You can tweak around this).
Where are you updating the file_t->size when you write into a file?
You are calling this:
fwrite(str, sizeof(char), strlen(str), p->f);
But after that you should do p->size += strlen(str) to update its size, otherwise all file sizes are set to initial values, and hence all strings get written to a single file.
As for getting garbage data, try printing the string you are reading from scanf in the while loop.
You are using scanf to read characters until '\n', but you are not reading the '\n' itself. You need a fseek(stdin, 0, SEEK_END); in that loop as well.
Finally, why are you using syntax like this:
(files + i)->size
When you can call it more cleanly like this:
files[i].size
You code is really hard to read because of this.
I'm getting the following error when freeing "shifted_text" below. I've checked with print statements and commenting things out, and it's definitely that free(shifted_text). The other free commands are working fine.
Debug Error!
HEAP CORRUPTION DETECTED: After normal block (#77) at 0x007D1F...
CRT detected that the application wrote to memory after end of heap buffer.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void parse(int argc, char *argv[]);
char * shift_text(char *sometext);
char shift_letter(char letter, char shift);
void bring_in_text(void);
void write_to_file(char *sometext);
char *flag;
char *password;
char *text;
int main(int argc, char *argv[])
{
parse(argc, argv);
char *shifted_text;
// at this point flag can only be -e, -d, -df, -ef
if (strcmp(flag, "-e") == 0 || strcmp(flag, "-d") == 0)
{
// location to store the shifted text
shifted_text = (char*)malloc(strlen(text) * sizeof(char));
shift_text(shifted_text);
printf("%s\n", shifted_text);
}
else
{
bring_in_text();
// location to store the shifted text
shifted_text = (char*)malloc(strlen(text) * sizeof(char));
shift_text(shifted_text);
write_to_file(shifted_text);
}
free(shifted_text);
free(text);
free(flag);
free(password);
return 0;
}
void write_to_file(char *sometext)
{
if (strcmp(flag, "-df") == 0)
{
FILE *fp;
fp = fopen("plaintext.txt", "w");
if (fp == NULL)
{
puts("Unable to open file");
exit(1);
}
fprintf(fp, sometext);
fclose(fp);
}
else if (strcmp(flag, "-ef") == 0)
{
FILE *fp;
fp = fopen("ciphertext.txt", "w");
if (fp == NULL)
{
puts("Unable to open file");
exit(1);
}
fprintf(fp, sometext);
fclose(fp);
}
}
void bring_in_text(void)
{
if (strcmp(flag, "-df") == 0)
{
FILE *fp;
fp = fopen("ciphertext.txt", "r");
if (fp == NULL)
{
puts("Unable to open file");
exit(1);
}
while (!feof(fp))
{
text = (char*)malloc(100 * sizeof(char));
fgets(text, 100, fp);
}
fclose(fp);
}
else if (strcmp(flag, "-ef") == 0)
{
FILE *fp;
fp = fopen("plaintext.txt", "r");
if (fp == NULL)
{
puts("Unable to open file");
exit(1);
}
while (!feof(fp))
{
text = (char*)malloc(100 * sizeof(char));
fgets(text, 100, fp);
}
fclose(fp);
}
}
char * shift_text(char *shifted_text)
{
char *temptext;
temptext = text;
char *tempshiftedtext;
tempshiftedtext = shifted_text;
// space for 10 characters plus null
char *temppswd;
temppswd = password;
for (int i = 0; i < strlen(text); i++)
{
char a;
if (*temptext >= 97 && *temptext <= 122)
{
a = shift_letter(*(temptext + i), *(temppswd + (i % strlen(password))));
*(tempshiftedtext + i) = a;
}
else
*(tempshiftedtext + i) = *(temptext + i);
}
*(tempshiftedtext + strlen(text)) = '\0';
}
char shift_letter(char letter, char shift)
{
if (strcmp(flag, "-e") == 0 || strcmp(flag, "-ef") == 0)
{
letter = letter - 97;
shift = shift - 97;
int shifted_letter = letter + shift;
if (shifted_letter > 25)
shifted_letter %= 26;
shifted_letter += 97;
return (char)shifted_letter;
}
else if (strcmp(flag, "-d") == 0 || strcmp(flag, "-df") == 0)
{
int shifted_letter = letter - 97;
shift = shift - 97;
int letter = shifted_letter - shift;
letter %= 26; // mod seems to allow negative results, so if its still negative. add another val equal to modulus
if (letter < 0)
letter += 26;
letter += 97;
return (char)letter;
}
}
void parse(int argc, char *argv[])
{
if (argc == 4)
{
// internally calls malloc on strlen(argv[i])
flag = _strdup(argv[1]);
password = _strdup(argv[2]);
text = _strdup(argv[3]);
if (strlen(password) > 10)
{
puts("Password too long");
exit(1);
}
else if (strcmp(flag, "-e") != 0 && strcmp(flag, "-d") != 0)
{
puts("Incorrect flag");
exit(1);
}
}
else if (argc == 3)
{
// internally calls malloc on strlen(argv[i])
flag = _strdup(argv[1]);
password = _strdup(argv[2]);
if (strlen(password) > 10)
{
puts("Password too long");
exit(1);
}
else if (strcmp(flag, "-ef") != 0 && strcmp(flag, "-df") != 0)
{
puts("Incorrect flag");
exit(1);
}
}
else
{
puts("Incorrect arguements");
exit(1);
}
}
The functions parse simply stores command line arguments in the global's. The shifting functions shift a letter by some number. 'A' shifted by 2 would be 'C' for example. These work fine and without the free(shifted_text) the program works.
I'm new to C so it's probably something simple but I can't see it.
Change this
shifted_text = (char*)malloc(strlen(text) * sizeof(char));
to
shifted_text = malloc((strlen(text) + 1) * sizeof(char)); // don't cast
A C-style string always has a null-terminator, indicating the end of the string. For example, "foo" is stored as 'f', 'o', 'o', '\0' in memory. So you have to
I suspect that the heap buffer corruption isn't caused by your free(shifted_text);. Since insufficient memory is allocated to shifted_text, undefined behaviour is invoked, making everything possible. So your program may either run properly or crash. Perhaps it's only a coincidence that every time free(shifted_text); is commented out, your program runs correctly thanks to the undefined behaviour.
BTW: There are many places in your code to be refined. For example, in void bring_in_text(void):
while (!feof(fp))
{
text = (char*)malloc(100 * sizeof(char));
fgets(text, 100, fp);
}
Covering the previous lines without even processing them? Also, text isn't freed in this function.
strdup allocates strlen+1 chars and you only allocate strlen chars. When you write the null at the end of shifted text you are overflowing the buffer.
I have a code that scans all the files in a directory for targeted words, and prints them out into a new file. The problem right now is after the while loop reads a file and stores a variable into the string (ex. customer), if the next file being read does not have the targeted word, it still displays the result stored in the string from the previous file. My goal is to make it display "N/A" if the current file does not have the target word.
I have tried a few ways to clear the string at the end or beginning of the while loop, but none of them work most of them just gives me a coredump error. Running out of ideas, any help would be much appreciated!
Code (shortened for easier reading):
int main(int argc, char** argv)
{
char directory[100];
char buff[100];
char delims[] = " :=";
char* result = NULL;
char* customer;
char* device;
char* buffer;
int i = 0;
DIR* FD;
struct dirent* in_file;
int c = 0;
printf("Enter directory:");
scanf("%s",directory);
FILE* ft = fopen("workorderlist.csv", "w"); /* Open file to write to*/
if (ft == NULL)
{
puts("Cannot open target file");
exit(1);
}
fprintf (ft, "Work Order,Customer,Device,Test_Prog,Software,DUT_board_id,Corl box\n");
/* Open Directory */
if (NULL == (FD = opendir(directory)))
{
puts("Cannot open directory");
return 1;
}
while ((in_file = readdir(FD)))
{
if (!strcmp (in_file->d_name, "."))
{
continue;
}
if (!strcmp (in_file->d_name, ".."))
{
continue;
}
/* Open files to read from */
buffer = (char*)malloc(100);
sprintf(buffer, "%s/%s", directory, in_file->d_name);
size_t len = strlen(buffer);
if (len >= 4 && memcmp(buffer + len - 4, ".wor", 4) == 0) /* checks if file ends with .wor */
{
FILE* fs = fopen(buffer, "r"); /* open file to read */
if (fs == NULL)
{
puts("Cannot open source file");
return 1;
}
/* Scanning each file for targeted words: */
while (fgets(buff, 100, fs) != NULL)
{
result = strtok( buff, delims );
while (result != NULL)
{
if ((strcmp(result, "Customer") == 0))
{
result = strtok(NULL,delims);
customer = (char*)malloc((strlen(result)+1)*sizeof(char));
strcpy(customer, result);
for (i = 0; i < strlen(customer) + 1; i++)
{
if (customer[i] == '\n')
{
break;
}
}
customer[i] = ' ';
}
if (strcmp(result, "device") == 0)
{
result = strtok(NULL, delims);
device = (char*)malloc((strlen(result) + 1) * sizeof(char));
strcpy(device, result);
for (i = 0; i < strlen(device) + 1; i++)
{
if(device[i] == '\n')
{
break;
}
}
device[i] = ' ';
}
result = strtok(NULL,delims);
}
}
if (customer == '\0')
{
customer = "N/A";
}
if (device == '\0')
{
device = "N/A";
}
fprintf(ft, "%s,%s,%s,%s,%s,%s,%s\n",
in_file->d_name, customer, device, testprog,
software, dutboardid, corlbox);
printf(in_file->d_name);
printf("\n");
fclose (fs) ;
c++;
}
}
printf("Total Workorders Found: %d (Info saved to workorderlist.csv)\n", c);
fclose(ft);
return 0;
}
First at all, customer/device are strings. You should not be doing == for it comparison. You can, for example, compare the first char of the string: device[0] == '\0';
You should do string initialization before the loop starts.
You can achieve this by using strcpy with a known value or any other string manipulation function. The value that you use to initialize the string before the loop is the one you gonna test with strcmp or similar later.
Is like with ints or any other C data type, but you need manipulation functions instead.
By the way, haven't you posted your read file loop in a question here too?
Hope this helps.