Trying to write numbers from a .txt to a binary file - c

I am currently reading a text file that is below:
New York,4:20,3:03
Kansas City,12:03,3:00
North Bay,16:00,0:20
Kapuskasing,10:00,4:02
Thunder Bay,0:32,0:31
I have the city names being fprintf to a new .txt file which works fine, however I am trying to take the times and print them to a binary file and am stuck as to where I am having an issue. Any help would be appreciated.I need to store the times as 04, 20 for "New York" in a 2 byte value and having issues parsing to have this specifically.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#pragma warning(disable: 4996)
// a function to remove the trailing carraige return
void clearTrailingCarraigeReturn(char* buffer);
/* == FUNCTION PROTOTYPES == */
/* == CONSTANTS == */
// MAIN
typedef struct
{
char cityName[20];
short flightTime;
short layoverTime;
} Flight;
Flight parseFlight(char* line) {
char delimiter[2] = ",";
Flight flight;
char* token = strtok(line, delimiter);
int i = 0;
while (token != NULL)
{
if (i == 0)
{
strcpy(flight.cityName, token);
}
if (i == 1)
{
flight.flightTime = atoi(token);
}
if (i == 2)
{
flight.layoverTime = atoi(token);
}
token = strtok(NULL, delimiter);
i++;
}
return flight;
}
int main(int argc, char* argv[])
{
FILE *fpIn, *fpOut, *fbOut;
char line[80];
Flight flight;
fpIn = fopen(argv[1], "r");
fpOut = fopen("theCities.txt", "w+");
fbOut = fopen("theTimes.dat", "wb+");
while (fgets(line, 1024, fpIn) > 0)
{
clearTrailingCarraigeReturn(line);
printf(" >>> read record [%s]\n", line);
flight = parseFlight(line);
fprintf(fpOut, "%s\n", flight.cityName);
fwrite(&flight.flightTime, sizeof(short), 1, fbOut);
fwrite(&flight.layoverTime, sizeof(short), 1, fbOut);
}
fclose(fpIn);
fclose(fpOut);
fclose(fbOut);
}
// This function locates any carraige return that exists in a record
// and removes it ...
void clearTrailingCarraigeReturn(char* buffer)
{
char* whereCR = strchr(buffer, '\n');
if (whereCR != NULL)
{
*whereCR = '\0';
}
}

Perhaps something like:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Time_s
{
unsigned char hours;
unsigned char minutes;
} Time_t;
typedef struct Flight_s
{
char cityName[20];
Time_t flightTime;
Time_t layoverTime;
} Flight_t;
// a function to remove the trailing carraige return
void clearTrailingCarraigeReturn(char *buffer)
{
int more;
do {
size_t index;
index = strlen(buffer);
if(!index)
break;
--index;
switch(buffer[index])
{
case '\n':
case '\r':
buffer[index] = '\0';
more = 1;
break;
default:
more = 0;
break;
}
} while(more);
return;
}
int ParseTime(char *timeStr, Time_t *time)
{
int rCode=0;
char *next;
time->hours = (unsigned char)strtoul(timeStr, &next, 10);
if(':' == *next)
{
++next;
time->minutes = (unsigned char)strtoul(next, NULL, 10);
}
return(rCode);
}
Flight_t parseFlight(char* line)
{
char delimiter[2] = ",";
Flight_t flight;
char *token = strtok(line, delimiter);
int i = 0;
while(token)
{
switch(i)
{
case 0:
strcpy(flight.cityName, token);
break;
case 1:
ParseTime(token, &flight.flightTime);
break;
case 2:
ParseTime(token, &flight.layoverTime);
break;
}
token = strtok(NULL, delimiter);
i++;
}
return(flight);
}
int main(int argc, char* argv[])
{
int rCode=0;
FILE *fpIn=NULL, *fpOut=NULL, *fbOut=NULL;
char line[80+1];
Flight_t flight;
if(argc < 2)
{
fprintf(stderr, "ERROR: argc < 2\n");
goto CLEANUP;
}
fpIn = fopen(argv[1], "r");
if(!fpIn)
{
fprintf(stderr, "ERROR: fopen(\"%s\",\"r\")\n", argv[1]);
goto CLEANUP;
}
fpOut = fopen("theCities.txt", "w+");
if(!fpOut)
{
fprintf(stderr, "ERROR: fopen(\"theCities.txt\",\"w+\")\n");
goto CLEANUP;
}
fbOut = fopen("theTimes.dat", "wb+");
if(!fbOut)
{
fprintf(stderr, "ERROR: fopen(\"theTimes.dat\",\"wb+\")\n");
goto CLEANUP;
}
while(fgets(line, sizeof(line), fpIn) > 0)
{
clearTrailingCarraigeReturn(line);
flight = parseFlight(line);
printf("%s,%02hhu:%02hhu,%02hhu:%02hhu\n",
flight.cityName,
flight.flightTime.hours, flight.flightTime.minutes,
flight.layoverTime.hours, flight.layoverTime.minutes
);
fprintf(fpOut, "%s\n", flight.cityName);
fwrite(&flight.flightTime, sizeof(Time_t), 1, fbOut);
fwrite(&flight.layoverTime, sizeof(Time_t), 1, fbOut);
}
CLEANUP:
if(fpIn)
fclose(fpIn);
if(fpOut)
fclose(fpOut);
if(fbOut)
fclose(fbOut);
return(rCode);
}

Related

Warnings and segmentation fault core dumped

This is a program to remove particular lines in a file. It copies the lines which are needed and prints it in another file in the same directory. I'm not getting any errors except for warnings such as incompatible pointer type [-Wincompatible-pointer-types]. When I run the code I also get the prtintf statement but when entered input Segmentation fault (core dumped). Is it related to the warnings or is it something else ?
code
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<stdbool.h>
#include <ctype.h>
char *name_find(char *buf[], char *name[]) {
const char *p = NULL;
size_t len = strlen(name);
if (len > 0) {
for (p = buf ; (p = strstr(p, name)) != NULL; p++) {
if (p == buf || !isalnum((unsigned char)p[-1])) {
if (!isalnum((unsigned char)p[len]))
break; /* we have a match! */
p += len; /* next match is at least len+1 bytes away */
}
}
}
return p;
}
int main()
{
char name[25];
char buf[100];
setenv("PFILE","/home/ashwin/Desktop/FILE/",1);
char ori_path[100],new_path[100];
if (!getenv("PFILE")){
}
else{
strcpy(ori_path, getenv("PFILE"));
strcpy(new_path, getenv("PFILE"));
strcat(ori_path, "shadow");
strcat(new_path, "shadow1");
}
bool success=false;
printf("Enter the command\n ");
printf("userdel ");
FILE *fold = fopen(ori_path, "r"); // old file
FILE *fnew = fopen(new_path, "w"); // new temp file
fgets(name,25,stdin);
for(int i = 0; i < strlen(name); i++)
{
if(name[i] == '\n')
{
name[i] = '\0';
break;
}
}
while (fgets(buf, 100, fold)) {
// read lines until error or EOF
if (!name_find(buf, name)) {
fprintf(fnew, "%s", buf);
success=true;
}
}
if(success){
printf("Success !!!\n");
}
return 0;
}
char *name_find(char *buf[], char *name[])
You use char *buf[], which means buf is an array of pointers to char, not a pointer to char. Use char* buf instead. Same goes for name.
Additionally:
FILE *fold = fopen(ori_path, "r"); // old file
FILE *fnew = fopen(new_path, "w"); // new temp file
You should check if the opening of the streams to the files were successful by checking the returned pointers for a null pointer:
FILE *fold = fopen(ori_path, "r"); // old file
if(!fold)
{
fputs("Error at opening fold!", stderr);
exit(1);
}
FILE *fnew = fopen(new_path, "w"); // new temp file
if(!fnew)
{
fputs("Error at opening fnew!", stderr);
exit(1);
}
Try this code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <ctype.h>
char *name_find(char *buf, char *name) {
const char *p = NULL;
size_t len = strlen(name);
if (len > 0) {
for (p = buf ; (p = strstr(p, name)) != NULL; p++) {
if (p == buf || !isalnum((unsigned char)p[-1])) {
if (!isalnum((unsigned char)p[len]))
break; /* we have a match! */
p += len; /* next match is at least len+1 bytes away */
}
}
}
return p;
}
int main (void)
{
char name[25];
char buf[100];
setenv("PFILE","/home/ashwin/Desktop/FILE/",1);
char ori_path[100],new_path[100];
if (!getenv("PFILE")){
}
else{
strcpy(ori_path, getenv("PFILE"));
strcpy(new_path, getenv("PFILE"));
strcat(ori_path, "shadow");
strcat(new_path, "shadow1");
}
bool success=false;
printf("Enter the command\n ");
printf("userdel ");
FILE *fold = fopen(ori_path, "r"); // old file
if(!fold)
{
fputs("Error at opening fold!", stderr);
exit(1);
}
FILE *fnew = fopen(new_path, "w"); // new temp file
if(!fnew)
{
fputs("Error at opening fnew!", stderr);
exit(1);
}
fgets(name,25,stdin);
for(unsigned int i = 0; i < strlen(name); i++)
{
if(name[i] == '\n')
{
name[i] = '\0';
break;
}
}
while (fgets(buf, 100, fold)) {
// read lines until error or EOF
if (!name_find(buf, name)) {
fprintf(fnew, "%s", buf);
success=true;
}
}
if(success){
printf("Success !!!\n");
}
return 0;
}

How to parse and arrange lines of a csv file based on matching word in C?

I have csv file with below format :
name,birthmonth,country,hobby
jack,jan,england,soccer
roben,july,germany,soccer
emma,dec,china,tennis
yannick,sep,france,music
alex,nov,england,cricket
thomas,apr,germany,tennis
mike,oct,netherlands,cycling
michelle,feb,france,poetry
yui,mar,japan,coding
feng,jun,china,reading
I want to parse this file using C, and put all the lines with same country name in a consecutive manner i.e shown below:
name,birthmonth,country,hobby
jack,jan,england,soccer
alex,nov,england,cricket
roben,july,germany,soccer
thomas,apr,germany,tennis
emma,dec,china,tennis
feng,jun,china,reading
yannick,sep,france,music
michelle,feb,france,poetry
mike,oct,netherlands,cycling
yui,mar,japan,coding
So far, I have tried this code below, however not able to match things properly and proceed further:
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<fcntl.h>
#include<string.h>
int main (int argc, char **argv) {
//int line;
char line[200];
char *inputFile = argv[1];
FILE *input_csv_file;
char a,b,c,d,e;
input_csv_file = fopen(inputFile, "rt");
if(input_csv_file ==0) {
printf("Can not open input file \n");
}
else {
//while((line = fgetc(input_csv_file)) != EOF) {
while(fgets(line, sizeof line, input_csv_file) != NULL) {
printf ("line = %s\n", line);
if(sscanf(line, "%s,%s,%s,%s,%s", a,b,c,d,e)) {
//if(sscanf(line, "%[^,], %[^,], %[^,], %[^,], %[^,]", a,b,c,d,e)) {
printf("d=%s\n",d);
}
}
}
return 0;
}
I am a newbie in C/C++. Any help would be much appreciated
Thanks.
I could write the code to get the required output. Below is the code:
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<fcntl.h>
#include<string.h>
int main(int argc, char ** argv)
{
struct filedata {
char nation[8];
char content[50];
};
char line[100];
char *inputFile = argv[1];
FILE *input_csv_file;
int iter = 0, c;
char * tok;
int count = 0;
char ch;
char country[] = "country";
char header_line[50];
input_csv_file = fopen(inputFile, "rt");
//count line numbers of the input csv
for(ch = getc(input_csv_file); ch!= EOF; ch=getc(input_csv_file))
if(ch == '\n')
count = count + 1;
fclose(input_csv_file);
count = count -1;
struct filedata * record[count];
input_csv_file = fopen(inputFile, "rt");
if(input_csv_file == 0)
{
printf("Can not open input file\n");
} else
{
while(fgets(line, sizeof line, input_csv_file) != NULL)
{
//printf("-- line = %s\n", line);
int s_line = sizeof line;
char dup_line[s_line];
strcpy(dup_line, line);
int h = 0;
int s_token;
tok = strtok(line, ",");
while(tok != NULL)
{
h++;
if(h == 3)
{
s_token = sizeof tok;
break;
}
tok = strtok(NULL, ",");
}
// skipping the line having column headers
if(compare_col(tok, country) == 0) {
strcpy(header_line, dup_line);
continue;
}
iter++;
c = iter - 1;
record[c] = (struct filedata*)malloc(sizeof(struct filedata));
strcpy(record[c]->nation, tok);
strcpy(record[c]->content, dup_line);
} //while
struct filedata * temp;
FILE * fptr;
fptr = fopen("nation_csv.txt", "w");
if(fptr == NULL)
{
printf("Error in opening the file to write\n");
exit(1);
}
// sorting the arr of struct nation wise
for(iter=1; iter < count; iter++)
for(c =0 ; c < count -1; c++) {
if(strcmp(record[c]->nation, record[c+1]->nation) > 0) {
temp = record[c];
record[c] = record[c+1];
record[c+1] = temp;
}
}
for(iter=0; iter < count; ++iter)
{
if(iter == 0) {
fprintf(fptr, "%s", header_line);
continue;
}
fprintf(fptr, "%s", record[iter]->content);
}
fclose(fptr);
}
fclose(input_csv_file);
}
int compare_col(char a[], char b[] )
{
int c = 0;
while(a[c] == b[c]) {
if(a[c] == '\0' || b[c] == '\0')
break;
c++;
}
if(a[c] == '\0' && b[c] == '\0')
return 0;
else
return -1;
}
Thanks for all your inputs. Any further inputs to make it better are much appreciated.
Thanks

Segmentation faulting in assignment

I'm currently learning C and I came from java. Our assignment asked us to count strings from either a file that could be added or it asks for the user to input a string. We just started using pointers and i looked up the different reasons why segmentation faults happened but I have no idea how to check for which issue it is. I initialized all my pointers to NULL but it still didn't work and from what i read that was the most common reason why a segmentation fault happens.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int debug = 0;
int
main(int argc, char **argv)
{
extern char *optarg;
extern int optind;
FILE* infile = NULL;
int c, err = 0;
int lflag = 0, sflag = 0, count = 0; //flags and count
char *shortWord = NULL, *longWord = NULL; //variable for shortest and longest word
int shortest = 100, longest = 0; //longest char 100, shortest 0
char *string = NULL;
char *pch = NULL;
static char usage[] = "usage: %s [-l] [-s] [filename]\n";
while ((c = getopt(argc, argv, "ls")) != -1)
switch (c)
{
case 'l':
lflag = 1;
break;
case 's':
sflag = 1;
break;
case '?':
err = 1;
break;
}
if (err)
{
fprintf(stderr, usage, argv[0]);
exit(1);
}
//checks for file and then runs loop for word count
infile = fopen("myfile.txt","r");
if (infile != NULL)
{
fgets(string, 100, infile);
pch = strtok (string, " ,.-");
while(pch != NULL)
{
count++;
if (strlen(pch) > longest)
longWord = pch;
if (strlen(pch) < shortest)
shortWord = pch;
pch = strtok (NULL, " ,.");
}
}
//else, asks for string
else
{
printf("Enter your string: \n");
fgets(string, 100, stdin);
int len = strlen(string);
count = len;
pch = strtok ( string, " ,.-");
while(pch != NULL)
{
count++;
if (strlen(pch) > longest)
longWord = pch;
if (strlen(pch) < shortest)
shortWord = pch;
pch = strtok (NULL, " ,.");
}
}
//following lines compute value based on arguments
if(lflag == 1)
{
printf("Longest word is %s", longWord);
}
if(sflag == 1)
{
printf("Shortest word is %s", shortWord);
}
printf("Word count = %.2d\n", count);
exit(0);
}
Their are some issues in your code:
You initialized string to NULL, then used it as an input buffer for fgets(). fgets() reqiures a pointer to an array of chars, either declared on the stack or dynamically allocated with malloc(3). You can set an input buffer such as char string[100].
fgets() must be checked, as it returns NULL when unable to read a line.
Your delimiter for strtok() is not accounting for the \n character appended by fgets(). You can either remove this newline, or include it in the delimter. If you want to include it in the delimeter, make sure your delimiter is " ,.-\n".
You could create function which parses your input with strtok(), as this would allow your main() to be shorter and reduce the repetitiveness in the code. An example function prototype could be void longest_shortest_words(char line[], char **longest, char **shortest, size_t *word_count);, whereby you pass the longest, shortest words along with the number of words back to main() via pointers. You could also just store the longest and shortest words in a 2D array or array of pointers.
You should also explicitly check that your file was opened correctly. Something like this should be included:
infile = fopen("myfile.txt", "r");
if (infile == NULL) {
fprintf(stderr, "Failed to open file\n");
exit(EXIT_FAILURE);
}
When checking opt, checking ? as a character in your switch statement is not right. Instead of:
case '?':
err = 1;
break;
Use default, which covers any other invalid option entered. Here is how you can use it:
default:
fprintf(stderr, "usage: %s [-l] [-s] [filename]\n", argv[0]);
exit(EXIT_FAILURE);
Checking sflag and lflag at the end is not enough. You should check if longWord and shortWord are not NULL.
Here is some example code which demonstrates these points:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define LINESIZE 100
void longest_shortest_words(char line[], char **longest, char **shortest, size_t *wordcount);
void print_output(int lflag, int sflag, char *longword, char *shortword, size_t wordcount);
void remove_newline(char line[]);
int main(int argc, char * const argv[]) {
FILE *infile;
char line[LINESIZE] = {'\0'};
int opt, sflag = 0, lflag = 0;
size_t wordcount = 0;
const char *optstr = "ls";
char *longword = NULL, *shortword = NULL;
while ((opt = getopt(argc, argv, optstr)) != -1) {
switch(opt) {
case 'l':
lflag = 1;
break;
case 's':
sflag = 1;
break;
default:
fprintf(stderr, "usage: %s [-l] [-s] [filename]\n", argv[0]);
exit(EXIT_FAILURE);
}
}
/* Checking if file is in directory */
infile = fopen("myfile.txt", "r");
if (infile == NULL) {
fprintf(stderr, "Failed to open file\n");
exit(EXIT_FAILURE);
}
/* checking if line exists in file */
if (fgets(line, LINESIZE, infile) == NULL) {
fprintf(stderr, "No line found in file.\n");
printf("\nEnter string instead:\n");
if (fgets(line, LINESIZE, stdin) != NULL) {
remove_newline(line);
longest_shortest_words(line, &longword, &shortword, &wordcount);
/* checking that longWord, shortWord and word_count are valid */
if (longword != NULL && shortword != NULL && wordcount > 0) {
print_output(lflag, sflag, longword, shortword, wordcount);
}
}
/* file has line, do stuff with it */
} else {
remove_newline(line);
longest_shortest_words(line, &longword, &shortword, &wordcount);
print_output(lflag, sflag, longword, shortword, wordcount);
}
exit(EXIT_SUCCESS);
}
/* function for printing output, can be improved */
void print_output(int lflag, int sflag, char *longword, char *shortword, size_t wordcount) {
if (lflag) {
printf("Longest word: %s\n", longword);
}
if (sflag) {
printf("Shortest word: %s\n", shortword);
}
if (wordcount > 0) {
printf("Word count = %zu\n", wordcount);
}
}
/* function for removing newline, and checking that input hasnt exceeded limit */
void remove_newline(char line[]) {
size_t slen;
slen = strlen(line);
if (slen > 0 && line[slen-1] == '\n') {
line[slen-1] = '\0';
} else {
fprintf(stderr, "\nToo many characters in input.\n");
exit(EXIT_FAILURE);
}
}
/* function which parses line, and saves longWord and shortWord in pointers */
void longest_shortest_words(char line[], char **longword, char **shortword, size_t *wordcount) {
char *word = NULL;
const char *delim = " ,.";
word = strtok(line, delim);
if (word != NULL) {
*longword = word;
*shortword = word;
*wordcount = 1;
}
while ((word = strtok(NULL, delim)) != NULL) {
(*wordcount)++;
if (strlen(word) > strlen(*longword)) {
*longword = word;
} else if (strlen(word) < strlen(*shortword)) {
*shortword = word;
}
}
}
Note: The code shown above can be improved, it is just to show you another approach to your problem.

Program to print and sum numbers in a text file

I want to write a program which print all numbers found in a file and then add them up. I have two problems:
How to add up the numbers I've printed?
Why in output_file do I have so many commas:
Here's my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define CHUNK 12
char *getWord(FILE *infile);
void clean(char *dirty);
char *getWord(FILE *infile)
{
char *word, *word2;
int length, cursor, c;
word = (char*)malloc(sizeof(char)*CHUNK);
if(word == NULL) return NULL;
length = CHUNK;
cursor = 0;
while(!isspace(c = getc(infile)) && !feof(infile))
{
word[cursor] = c;
cursor++;
if(cursor >= length)
{
length += CHUNK;
word2 = (char*)realloc(word, cursor);
if(word2 == NULL)
{
free(word2);
return NULL;
}
else
{
word = word2;
}
}
}
word[cursor] = '\0';
return word;
}
void clean(char *dirty)
{
int i = 0, j = 0;
char *temp;
temp = strdup(dirty);
while(i < strlen(temp))
{
if(isdigit(temp[i]))
{
dirty[j] = temp[i];
j++;
}
i++;
}
dirty[j] = '\0';
free(temp);
}
int main(int argc, char *argv[])
{
char *word;
FILE *infile, *outfile;
if(argc != 3)
{
printf("Missing argument!\n");
exit(1);
}
infile = fopen(argv[1], "r");
if(infile != NULL)
{
outfile = fopen(argv[2], "w");
if(outfile == NULL)
{
printf("Error, cannot open the outfile!\n");
abort();
}
else
{
while(!feof(infile))
{
word = getWord(infile);
if(word == NULL)
{
free(word);
abort();
}
clean(word);
fputs(word, outfile);
fputs(",", outfile);
free(word);
}
}
}
else
{
printf("Error, cannot open the outfile!\n");
abort();
}
fclose(infile);
fclose(outfile);
return 0;
}
infile:
You are getting , because of this -
fputs(",", outfile);
It is related in structure to the echo unix command. The core of the program could be simplified to something along the following lines:
int c, need_comma = 0;
while ((c = fgetc(infile)) != EOF) {
if (isdigit(c)) {
fputc(c, outfile);
need_comma = 1;
}
else {
if (need_comma == 1) {
fputc(',', outfile);
need_comma = 0;
}
}
}
this removes the need for getWord and clean functions.
This is just the printing part. the intermediate file is in CSV format,
which is structured and easy to parse and add the numbers (and print the
result to another file).

Illegal instruction core dumped error after INSERT statement

I am just developing simple logic to parse an ; separated file as below, and insert its contents in a DB.
It's working fine, but at the last iteration of the INSERT statement, I get this error:
selfdiag4.0.1 (157): undefined instruction: pc=020000fa Illegal instruction (core dumped).
My code is as follows:
int fileread() {
char str1[1024];
unsigned char catId[25]="",catName[50]="",prefix[25]="",status[10]="";
char *ptr;
char temp[1024];
int i=1,t,rc=0;
char delims[]=";";
char filename[100] ="/mnt/jffs2/category.txt";
FILE *fp;
rc=0;
fp= fopen("/mnt/jffs2/category.txt","r");
if (fp == NULL) {
printf("No such file");
return 1;
}
while(fgets(str1,sizeof(str1),fp) !=NULL) {
ptr=strtok(str1,delims);
while(ptr != NULL) {
i=1;
memset(catId,0,sizeof(catId));
memset(catName,0,sizeof(catName));
memset(prefix,0,sizeof(prefix));
memset(status,0,sizeof(status));
while(ptr!=NULL && i<=8) {
strcpy(temp, ptr);
ptr = strtok(NULL,delims);
switch(i) {
case 2: strcpy(catId,temp);
break; //insert into categoryId
case 4: Strcpy(catName,temp);
break;
case 6: Strcpy(prefix,temp);
break;
case 8: strcpy(status,temp);
break;
default:break;
} //end switch
i++;
} //end while
rc=execute("INSERT INTO category(category_id,category_name,prefix,status) VALUES('%s','%s','%s','%s');",catId,catName,prefix,status);
printf("\nIn While Loop\n");
if (rc == 0) return error_handler(rc);
} // end while
}
fclose(fp);
return 0;
}
#include <stdio.h>
#include <string.h>
/* these are for testing */
#define execute printf
#define error_handler(i) fprintf(stderr, "Error(%d)\n", i )
int fileread(char *filename )
{
char buff[1024];
size_t off,len, cnt;
char *ptrs[10];
int rc=0;
char delims[]=";\n\r";
FILE *fp;
fp= fopen(filename, "r");
if (fp == NULL) {
fprintf(stderr, "No such file: %s\n", filename);
return 1;
}
while(fgets(buff,sizeof buff,fp) ) {
for(cnt=off = 0; buff[off] ; off+= len ) {
ptrs[cnt++] = buff + off;
len = strcspn(buff+off, delims );
if (!len) break;
buff[len+off] = '\0';
len += 1;
if (cnt >= 10) { fprintf(stderr, "Too many items\n" ); break; }
}
if (cnt < 8) continue;
/* if you expect repeating groups,
** you should iterate here. And resize ptrs[] */
rc=execute(
"INSERT INTO category(category_id,category_name,prefix,status)"
" VALUES('%s','%s','%s','%s');\n"
,ptrs[1],ptrs[3],ptrs[5],ptrs[7]);
if(rc == 0)return error_handler(rc);
}
fclose(fp);
return 0;
}
int main(void)
{
char *filename ="/mnt/jffs2/category.txt";
int rc;
rc = fileread (filename);
return 0;
}

Resources