please help iam struggling with open file and read/search, ONLY IN C language pl
ID: 3860909 • Letter: P
Question
please help iam struggling with open file and read/search, ONLY IN C language please.,
Problem:
Write a program that asks user to enter a character, then it searches through a file
named “test.txt” to see if that character
is
in
it
or
not.
The
program
should
return
number
of
times
that
character
occurs
within
the
file.
* ALSO...
You
need
to
write
a
function
that
takes
two
parameters,
a
character
and
a
pointer
to
the
file.
The
function
should
then
return
number
of
times
a
character
occurs
within
a
file.
Test
the
function
in
a
complete
program
(create
a
file
with
the
name
of
“test.txt”,
and
fill
it
with
some
contents
to
see
if
your
program
works
well
or
not!)
Explanation / Answer
char name;
int number;
FILE *f;
f = fopen("contacts.pcl", "a");
printf(" New contact name: ");
scanf("%s", &name);
printf("New contact number: ");
scanf("%i", &number);
fprintf(f, "%c [ %d ] ", name, number);
fclose(f);
FILE *f = fopen("file.txt", "w");
if (f == NULL)
{
printf("Error opening file! ");
exit(1);
}
/* print some text */
const char *text = "Write this to the file";
fprintf(f, "Some text: %s ", text);
/* print integers and floats */
int i = 1;
float py = 3.1415927;
fprintf(f, "Integer: %d, float: %f ", i, py);
/* printing single chatacters */
char c = 'A';
fprintf(f, "A character: %c ", c);
fclose(f);
FILE *fp;
char* str = "string";
int x = 10;
fp=fopen("test.txt", "w");
if(fp == NULL)
exit(-1);
fprintf(fp, "This is a string which is written to a file ");
fprintf(fp, "The string has %d words and keyword %s ", x, str);
fclose(fp);
============================================================================
int main(int argc, char *argv[]) {
int result, errno;
if(argc < 3 || argc > 3) {
Usage(argv[0]);
exit(1);
}
//Use system("cls") on windows
//Use system("clear") on Unix/Linux
system("cls");
result = Search_in_File(argv[1], argv[2]);
if(result == -1) {
perror("Error");
printf("Error number = %d ", errno);
exit(1);
}
return(0);
}
void Usage(char *filename) {
printf("Usage: %s <file> <string> ", filename);
printf("%s version 1.0 Copyright(c) CodingUnit.com ", filename);
}
int Search_in_File(char *fname, char *str) {
FILE *fp;
int line_num = 1;
int find_result = 0;
char temp[512];
//gcc users
//if((fp = fopen(fname, "r")) == NULL) {
// return(-1);
//}
//Visual Studio users
if((fopen_s(&fp, fname, "r")) != NULL) {
return(-1);
}
while(fgets(temp, 512, fp) != NULL) {
if((strstr(temp, str)) != NULL) {
printf("A match found on line: %d ", line_num);
printf(" %s ", temp);
find_result++;
}
line_num++;
}
if(find_result == 0) {
printf(" Sorry, couldn't find a match. ");
}
//Close the file if still open.
if(fp) {
fclose(fp);
}
return(0);
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.