Link to home
Start Free TrialLog in
Avatar of cap213
cap213

asked on

C: I/O File problems...

So I'm writing a program in C  and this one part is giving me trouble.  I want this function to find the first half of the line, which is set up 348247:title, with only the title. How would I accomplish this?(the title which I am comparing, is passed from another function)

int search(char title[81], int *stocknum[])
{
int j;
char tite[81];
FILE *va;
va = fopen("/Users/cap412/Desktop/videos.dat", "r");
for (j = 0; j < 50; j++){
fscanf(va, "%s", tite[j]);
if(strncmp(tite, title, 81) == 0)
fscanf(va, "%[0-9]", &stocknum[j]);
fclose(va);
}
}
Avatar of ozo
ozo
Flag of United States of America image

for (j = 0; j < 50; j++){
  fscanf(va, "%80s", tite);
  if( strstr(tite, title) )
    sscanf(tite, "%[0-9]",stocknum[j]);
}
  fclose(va);
Avatar of cap213
cap213

ASKER

Hrm...this only searches and inputs the first value in the database...maybe I'm doing something wrong when the user scans the title?

int getTitle(char title[81])
{
      printf("Please enter title to search or quit:  ");
      scanf("%s", title);
      return title;
}
ASKER CERTIFIED SOLUTION
Avatar of josgood
josgood
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Change the loop body to something like this

/* Get the line in */
char buffer[80];
fgets (buffer, sizeof (buffer), va);

/* Get the stock number - stops converting as soon as it hits a non numeric */
stocknum[j] = atoi (buffer);

/* Get title one char after the colon */
strcpy (title[i], strchr (buffer, ':') + 1);
I'd use this approach, a teensy bit slower but simpler:

int stocknumarray[10000];   char stocktitlearray[10000][80];  FILE * va;

va = fopen( "stockfile.txt", "r" ); tot = 0;

if( va != NULL ) {

while( not feof( va ) ) {
fscanf( va, "%d:%s", &stocknumarray[ tot ], stocktitlearray[ tot ]);
if(  strstr( title, WantedTitle ) != NULL )     tot++;
}

fclose( va );

>> maybe I'm doing something wrong when the user scans the title?
I guess so, looking at ur getTitle function since it is defined to return an int, but is actually returning a char [ ].