How toC: process files in a loop taking input from stdin
Discuss How toC: process files in a loop taking input from stdin in the C Programming forum on Dev Shed. How toC: process files in a loop taking input from stdin C programming forum discussing all C derivatives, including C#, C++, Object-C, and even plain old vanilla C. These languages are low level languages, and used on projects such as device drivers, compilers, and even whole computer operating systems.
Posts: 3
Time spent in forums: 41 m 35 sec
Reputation Power: 0
How toC: process files in a loop taking input from stdin
Hi I am new to C. I have to do an assignment where I have to take filenames as input and process each of them in a lop. What I am doing is taking the input in a space separated string (validations still incomplete) using strtok to retrieve individual filenames, putting them in an array, and processing each element of the array.
But when I am runnig the program, it is unable to open the last file inputted, though my debugging messages show that the last element contains the correct filename.
This is what I have got so far:
int main()
{
FILE *file;
int count;
char word[15] = {'\0'};
char query_string[256];
char *v_array[50];
int loop;
char *f_array[256];
printf("Enter the filenames to be searched separated by space\n");
fgets(query_string,sizeof(query_string),stdin);
f_array[0]=strtok(query_string," ");
printf("zeroth element is %s\n",f_array[0]);
if(f_array[0]==NULL)
{
printf("file not found\n");
return 0;
}
Posts: 249
Time spent in forums: 3 Days 17 h 55 m 47 sec
Reputation Power: 110
Apart from not putting your code into a code block, nice post!
I'd suggest that you take a closer look at what is actually stored as the third filename - I think if you look closely enough you'll see that it actually contains an added surprise. Try removing the file processing, and just printing the name of each file inside ' ' marks.
Hint: The solution is to add just 2 characters to your source file!!
Posts: 249
Time spent in forums: 3 Days 17 h 55 m 47 sec
Reputation Power: 110
Just change the delim string for strtok from " " to " \n" - make sure you do it for both of them, else it will fail - either when there's only 1 argument passed or when there's several, depending on which strtok you don't change.
Better make that add 4 characters to the source file - I didn't think through the fact that you'd need to change the delim string for both instances of strtok(I only changed it for the second).
[EDIT:] Yup, if you can compile while using strcspn, it'll work. As far as I know it's a part of the stdlib, so will be everywhere, unlike some of the nuggets found in TC's version of conio.h
Last edited by SimonB2 : August 27th, 2011 at 04:55 AM.