And this is the last incorrect code
Question:
Write a program that:
- Opens up each filename in argv[] for reading, starting from the second arg
ument
- - For each file, if the open fails, print, to stderr, the name of the file
that failed and an error message
- - - For each file that succeeds,
- - - Print out each line in the file to stdout, if that line contains the s
tring in argument 1
- - - At the front of the line, also print the name of the file it came from
, and the line number, separated by colons
- - - Close it
- Uses function prototypes:
- - int partial_match( char*, char* );
- - int find_string( char*, char* );
Example:
file.txt:
hello
world
this
is a test
file2.txt:
goodbye
world
this
is a test
so is this
and so on
we blissfully go
./prog is none.txt file.txt file1.txt
Error: could not open none.txt
file.txt:3:this
file.txt:4:is a test
file2.txt:3:this
file2.txt:4:is a test
file2.txt:5:so is this
file2.txt:7:we blissfully
- Note that the error was printed to stderr rather than stdout
- Note that this essentially only printed lines with "is" in them, from seve
ral files
Here's the pseudocode:
main:
for as long as we have arguments
open a file with filename of the current argument
if it opens successfully
for each line in the file
if it contains the word we're looking for
print the line
close the file
otherwise
print an error
contains:
for as long as we have non-null characters in a string
if the string starting from the current location partially matches the w
ord
true
by the end, if we never found it, false
partial-match:
for as long as we have characters in the word we're searching for
if the string's current character doesn't match the corresponding word's
current character
false
by the end, if we never found a discrepancy, true
Here's my incorrect code:
That's it! Thanks for your help!!!Code:#include <stdio.h> int partial_match (char* string1, char* string2); void find_string (char* find_this, char* within_this); int main (int argc, char** argv) { File* funny; int i = 2; char buffer [1024]; for (i=2; argv [i] != '\0'; i = i + 1) { funny = fopen (argv [i], "r"); if (funny != NULL) { while (fgets (buffer, 1024, funny)!= NULL) { find_string (argv [1], argv [i]); } fclose (funny); } fprintf (stdout, "no argument!\n"); } void find_string (char* find_this, char* within_this) { int j; for (j = 0; within_this[j] != '\0'; j = j + 1) { if (find_this[j] == &within_this[j] ) { return 1; } return 0; } } int partial_match (char* string1, char* string2) { in m; for (m = 0; string1[m] != '\0'; m = m+1) { if (string1 [m] != string2 [m]) { return 0; } return 1; } }