I am currently trying to read a file and count the number of instances of a user-specified string in an input file and output them to another file,.
However when I try to open the file, fopen returns NULL. Here's what I have so far:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv)
{
char in[50];
char out[50];
char target[50];
getIns(in,out,target);
Search(in, out, target);
//printf("string entered: %s\n%s\n%s", in, out, target);
return 0;
}
int getIns(char *i, char *o, char *t)
{
printf("please enter name of input file you wish to search: \n -i ");
fgets(i, 50, stdin);
printf("please enter name of output file you wish to write to: \n -o ");
fgets(o,50,stdin);
printf("Please enter the string you wish to search for \n -c ");
fgets(t, 50, stdin);
return 1;
}
int Search(char *i, char *o, char *t)
{
char*p;
int c = 0;
int start;
char *data = NULL;
FILE*f;
f = fopen(i, "r");
if (f == NULL)
{
printf("file not found \n Quitting...");
exit(1);
}
while(!feof(f))
{
fgets(data, sizeof(data), f);
p = strstr(data,t);
while (p != NULL)
{
c++;
p = strstr(p , t);
}
}
if (c == 0)
{
printf("String not in file\n");
}
if (c > 0)
{
printf("word: %s found: %d times\n", t, c);
}
fclose(f);
return 1;
}
Edit:
I've made some changes to the code following the responses and now, my program crashes on reading the file. New code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int Search(char *i, char *o, char *t)
{
char*p;
int c = 0;
int start;
char data[1024];
FILE*f;
f = fopen(i, "r");
if (f == NULL)
{
printf("file not found \n Quitting...");
exit(1);
}
while(fgets(data, sizeof(data), f))
{
fgets(data, sizeof(data), f);
p = strstr(data,t);
while (p != NULL)
c++; p = strstr(p+1 , t);
}
if (c == 0)
{
printf("String not in file\n");
}
if (c > 0)
{
printf("word: %s found: %d times\n", t, c);
}
fclose(f);
return 1;
}
int getIns(char *i, char *o, char *t)
{
printf("please enter name of input file you wish to search: \n -i ");
fgets(i, 50, stdin); i[strcspn(i, "\n")] = 0;
printf("please enter name of output file you wish to write to: \n -o ");
fgets(o, 50, stdin); o[strcspn(o, "\n")] = 0;
printf("Please enter the string you wish to search for \n -c ");
fgets(t, 50, stdin); t[strcspn(t, "\n")] = 0;
return 1;
}
int main(int argc, char **argv)
{
char in[50];
char out[50];
char target[50];
getIns(in,out,target);
Search(in, out, target);
return 0;
}
try this
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int getIns(char *i, char *o, char *t);
int Search(char *i, char *o, char *t);
int main(int argc, char **argv)
{
char in[50];
char out[50];
char target[50];
getIns(in,out,target);
Search(in, out, target);
//printf("string entered: %s\n%s\n%s", in, out, target);
return 0;
}
int getIns(char *i, char *o, char *t)
{
printf("please enter name of input file you wish to search: \n -i ");
fgets(i, 50, stdin);
i[strcspn(i, "\n")] = 0;
printf("please enter name of output file you wish to write to: \n -o ");
fgets(o,50,stdin);
o[strcspn(o, "\n")] = 0;
printf("Please enter the string you wish to search for \n -c ");
fgets(t, 50, stdin);
t[strcspn(t, "\n")] = 0;
return 1;
}
int Search(char *i, char *o, char *t)
{
char*p;
int c = 0;
int start;
char data[1024];
FILE*f;
f = fopen(i, "r");
if (f == NULL)
{
printf("file not found \n Quitting...");
exit(1);
}
while(fgets(data, sizeof(data), f)){
p = strstr(data,t);
while (p != NULL)
{
c++;
p = strstr(p+1 , t);
}
}
if (c == 0)
{
printf("String not in file\n");
}
if (c > 0)
{
printf("word: %s found: %d times\n", t, c);
}
fclose(f);
return 1;
}
Related
I am trying to store the values stored in a details.txt file into their appropriate place in a dynamically allocated struct. Am I doing something (that should be simple) incorrectly for this not to work? Is it necessary for me to use strtok and split by ','?
My details.txt reads:
mitch,8,1.78,burgers
murray,42,6.5,lasagna
travis,64,1.85,sushi
sam,12,1.94,bacon
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define BUFFERSIZE 256
typedef struct
{
char name[BUFFERSIZE];
int favnumber;
float height;
char favfood[BUFFERSIZE];
} Person;
void print_person(Person *p)
{
printf("name: %s\n", p->name);
printf("num: %d\nheight: %.2f\nfav. food: %s\n\n",
p->favnumber, p->height, p->favfood);
}
int count_lines(FILE *fp)
{
int nlines = 0;
char c;
for (c = fgetc(fp); c != EOF; c = fgetc(fp))
{
if (c == '\n')
{
nlines++;
}
}
rewind(fp);
return nlines;
}
int main(void)
{
FILE *fp = fopen("details.txt", "r");
// count lines
int nlines = count_lines(fp);
printf("found %d lines\n\n",nlines);
Person *people = (Person*)malloc(nlines*sizeof(Person));
char buffer[BUFFERSIZE];
int i = 0;
while (fgets(buffer,BUFFERSIZE,fp) != NULL)
{
sscanf(buffer,"%s%d%f%s",people[i].name,
&(people[i].favnumber),
&(people[i].height),people[i].favfood);
print_person(&(people[i]));
i++;
}
printf("found %d people\n",i);
free(people);
fclose(fp);
}
Unfortunately, the current output of my program is:
found 4 lines
name: mitch,8,1.78,burgers
num: 0
height: 0.00
fav. food:
...
found 4 people
The problem is that the first %s parse the the whole line, and you need , in the format string to separate the fields. Not an issue here yet but I also used %[^,] for the last format string so it will not stop at the first space. Also added precision on the strings to avoid buffer overflows:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define BUFFERSIZE 255
#define str(s) str2(s)
#define str2(s) #s
typedef struct
{
char name[BUFFERSIZE+1];
int favnumber;
float height;
char favfood[BUFFERSIZE+1];
} Person;
void print_person(Person *p)
{
printf("name: %s\n", p->name);
printf("num: %d\nheight: %.2f\nfav. food: %s\n\n",
p->favnumber, p->height, p->favfood);
}
int count_lines(FILE *fp)
{
int nlines = 0;
char c;
for (c = fgetc(fp); c != EOF; c = fgetc(fp))
{
if (c == '\n') {
nlines++;
}
}
rewind(fp);
return nlines;
}
int main(void)
{
FILE *fp = fopen("details.txt", "r");
// count lines
int nlines = count_lines(fp);
printf("found %d lines\n\n",nlines);
Person *people = (Person*)malloc(nlines*sizeof(Person));
char buffer[BUFFERSIZE+1];
int i = 0;
while (fgets(buffer,BUFFERSIZE+1,fp) != NULL)
{
// Changed line, see formatting of %s
sscanf(buffer,
"%" str(BUFFERSIZE) "[^,],%d,%f,%" str(BUFFERSSIZE) "[^,]",
people[i].name,
&(people[i].favnumber),
&(people[i].height),people[i].favfood);
print_person(&(people[i]));
i++;
}
printf("found %d people\n",i);
free(people);
fclose(fp);
}
can you advice me? I have a string from a file. When i see the string on my console, i need to write the word on which i want to change, and output the result in another file. For example: "Hello my girl" the word i want change "girl" on another word "boy". I can use the library
Can you advice me the algorithm which helps me to change the word?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char my_string[256];
char* ptr;
FILE *f;
if ((f = fopen("test.txt", "r"))==NULL) {
printf("Cannot open test file.\n");
exit(1);}
FILE *out;
if((out=fopen("result.txt","w"))==NULL){
printf("ERROR\n");
exit(1);
}
fgets (my_string,256,f);
printf ("result: %s\n",my_string);
ptr = strtok (my_string," ");
while (ptr != NULL)
{
printf ("%s \n",ptr);
ptr = strtok (NULL," ");
}
char old_word [10];
char new_word [10];
char* ptr_old;
char* ptr_new;
printf ("Enter your old word:\n");
ptr_old= gets (old_word);
printf ("Your old word:%s\n",old_word);
printf ("Enter new old word:\n");
ptr_new = gets (new_word);
printf ("Your new word:%s\n",new_word);
fclose(f);
fclose(out);
return 0;
}
i tried to split inputting string into words. Now its dead end.
This code will help you. you have to pass 4 args at runtime.
./a.out "oldword" "newword" "file name from take the old word" "file name where to copy"
$ ./a.out girl boy test.txt result.txt
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int args, char *argv[4])
{
FILE *f1;
FILE *f2;
char *strings=0;
char *newstrings=0;
char *token=NULL;
strings=(char *)malloc(1000);
newstrings=(char *)malloc(1000);
if((strings==NULL)||(newstrings==NULL))
{
printf("Memory allocation was not successfull.");
return 0;
}
if(args<4)
{
puts("Error: Not enough input parameters");
puts("Usage: ./change <oldword> <newword> <infile> <newfile>");
return 0;
}
f1=fopen(argv[3],"r");
f2=fopen(argv[4],"w");
if(f1==NULL)
{
puts("No such file exists");
return 0;
}
while(fgets(strings,1000,f1)!=NULL)
{
if(strstr(strings,argv[1])!=NULL)
{
token=strtok(strings,"\n\t ");
while(token!=NULL)
{
if(strcmp(token,argv[1])==0)
{
strcat(newstrings,argv[2]);
strcat(newstrings," ");
}
else
{
strcat(newstrings,token);
strcat(newstrings," ");
}
token=strtok(NULL,"\n\t ");
}
}
else
{
strcpy(newstrings,strings);
}
fputs(newstrings,f2);
}
free(strings);
free(newstrings);
printf("New file <%s> generated!\n",argv[4]);
fclose(f1);
fclose(f2);
return 0;
}
You can use a function like the shown function in the demonstrative program below
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
char * replace(const char *s, const char *src, const char *dsn)
{
size_t n = 0;
size_t src_len = strlen(src);
size_t dsn_len = strlen(dsn);
for (const char *p = s; (p = strstr(p, src)) != NULL; p += src_len)
{
n++;
}
char *result = malloc(strlen(s) + n * (src_len - dsn_len) + 1);
const char *p = s;
char *t = result;
if (n != 0)
{
for (const char *q; (q = strstr(p, src)) != NULL; p = q + src_len)
{
memcpy(t, p, q - p);
t += q - p;
memcpy(t, dsn, dsn_len);
t += dsn_len;
}
}
strcpy(t, p);
return result;
}
int main( void )
{
char s[] = " the girl and boy are relatives";
char *p = replace(s, "girl", "boy");
puts(s);
puts(p);
free(p);
}
The program output is
the girl and boy are relatives
the boy and boy are relatives
#include <stdio.h>
#include <string.h>
int main ()
{
char file_path[40] = { 0 }, stf[255] = { 0 }, rtf[255] = { 0 }, str[255] = { 0 };
FILE* file = NULL;
FILE *e_f;
if((e_f=fopen("result.txt","w"))==NULL){
printf("ERROR\n");
exit(1);
}
do
{
printf("Enter file path: ");
fgets(file_path, 40, stdin);
file_path[strlen(file_path) - 1] = '\0';
file = fopen(file_path, "r+");
}
while(file == NULL);
printf("Enter text to find: ");
fgets(stf, 255, stdin);
stf[strlen(stf) - 1] = '\0';
printf("Enter text to replace: ");
fgets(rtf, 255, stdin);
rtf[strlen(rtf) - 1] = '\0';
while(fgets(str, 255, file) != NULL)
{
char* tmp_ptr = strstr(str, stf);
while(tmp_ptr != NULL)
{
char tmp_str[255];
strcpy(tmp_str, tmp_ptr + strlen(stf));
strcpy(str + strlen(str) - strlen(tmp_ptr), rtf);
strcat(str, tmp_str);
tmp_ptr = strstr(str, stf);
}
printf("%s", str);
}
fclose(file);
fclose(e_f);
return 0;
}
That was i need. Thanks everybody for helping!
I did a function:
#include <stdio.h>
#include <string.h>
#define MAX 50
void Change (char x[], char cx, char nu){
int i;
for(i=0;i<strlen(x);i++) {
if (x[i]==cx){
x[i] = nu;
}
}
}
int main () {
char str[MAX];
char ch;
char new;
printf("Insert the string\n");
scanf("%s",str);
printf("Insert the word that you want to change\n");
scanf(" %c",&ch);
printf("the new word\n");
scanf(" %c",&new);
Change(str, ch, new);
printf("The new word is %s\n",str );
return 0;
}
I must modify my program to accept input from
a file called anagrams.txt.This file should have two strings per line, separated by the # character. My program should read
each pair of strings and report back if each pair of strings is an anagram. For example consider the following content of anagrams.txt:
hello#elloh
man#nam
Astro#Oastrrasd
Your program should print out the following:
hello#elloh - Anagrams!
man#nam - Anagrams!
Astro#Oastrrasd- Not anagrams!
I should compile in g++
Here is the code to read from text:
int main()
{
char input[30];
if(access( "anagrams.txt", F_OK ) != -1) {
FILE *ptr_file;
char buf[1000];
ptr_file =fopen("anagrams.txt","r"); if (!ptr_file)
return 1;
while (fgets(buf,1000, ptr_file)!=NULL)
printf("%s",buf);
fclose(ptr_file);
printf("\n");
}
else{ //if file does not exist
printf("\nFile not found!\n");
}
return 0;
}
Code to find if the text are anagrams:
#include <stdio.h>
int find_anagram(char [], char []);
int main()
{
char array1[100], array2[100];
int flag;
printf("Enter the string\n");
gets(array1);
printf("Enter another string\n");
gets(array2);
flag = find_anagram(array1, array2);
if (flag == 1)
printf(" %s and %s are anagrams.\n", array1, array2);
else
printf("%s and %s are not anagrams.\n", array1, array2);
return 0;
}
int find_anagram(char array1[], char array2[])
{
int num1[26] = {0}, num2[26] = {0}, i = 0;
while (array1[i] != '\0')
{
num1[array1[i] - 'a']++;
i++;
}
i = 0;
while (array2[i] != '\0')
{
num2[array2[i] -'a']++;
i++;
}
for (i = 0; i < 26; i++)
{
if (num1[i] != num2[i])
return 0;
}
return 1;
}
You can try something like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAXLINE 1000
#define MAXLETTER 256
int is_anagram(char *word1, char *word2);
void check_lines(FILE *filename);
int cmpfunc(const void *a, const void *b);
void convert_to_lowercase(char *word);
int
main(int argc, char const *argv[]) {
FILE *filename;
if ((filename = fopen("anagram.txt", "r")) == NULL) {
fprintf(stderr, "Error opening file\n");
exit(EXIT_FAILURE);
}
check_lines(filename);
fclose(filename);
return 0;
}
void
check_lines(FILE *filename) {
char line[MAXLINE];
char *word1, *word2, *copy1, *copy2;
while (fgets(line, MAXLINE, filename) != NULL) {
word1 = strtok(line, "#");
word2 = strtok(NULL, "\n");
copy1 = strdup(word1);
copy2 = strdup(word2);
convert_to_lowercase(copy1);
convert_to_lowercase(copy2);
if (is_anagram(copy1, copy2)) {
printf("%s#%s - Anagrams!\n", word1, word2);
} else {
printf("%s#%s - Not Anagrams!\n", word1, word2);
}
}
}
void
convert_to_lowercase(char *word) {
int i;
for (i = 0; word[i] != '\0'; i++) {
word[i] = tolower(word[i]);
}
}
int
is_anagram(char *word1, char *word2) {
qsort(word1, strlen(word1), sizeof(*word1), cmpfunc);
qsort(word2, strlen(word2), sizeof(*word2), cmpfunc);
if (strcmp(word1, word2) == 0) {
return 1;
}
return 0;
}
int
cmpfunc(const void *a, const void *b) {
if ((*(char*)a) < (*(char*)b)) {
return -1;
}
if ((*(char*)a) > (*(char*)b)) {
return +1;
}
return 0;
}
Since this looks like a University question, I won't provide a full solution, only a hint.
All you have to do is replace the stdin input part of the anagram-finding file with the code you wrote to read from a file: it's as simple as changing
printf("Enter the string\n");
gets(array1);
printf("Enter another string\n");
gets(array2);
to
// before program:
#define SIZE 1000
// inside main
if (access("anagrams.txt", F_OK) == -1){
printf("\nFile not found!\n");
return 1; // Abort the program early if we can't find the file
}
FILE *ptr_file;
char buf[1000];
ptr_file = fopen("anagrams.txt","r");
if (!ptr_file)
return 1;
char array1[SIZE], array2[SIZE];
while (fgets(buf, 1000, ptr_file)!=NULL){
// do all your anagram stuff here!
// there is currently one line of the input file stored in buf
// Hint: You need to split buf into array_1 and array_2 using '#' to separate it.
}
fclose(ptr_file);
printf("\n");
Additional comments:
Don't ever ever ever use gets. gets doesn't check that the string it writes to can hold the data, which will cause your program to crash if it gets input bigger than the array size. Use fgets(buf, BUF_SIZE, stdin) instead.
Beautiful code is good code. People are more likely to help if they can read your code easily. (fix your brackets)
Just for interest, a more efficient algorithm for checking anagrams is to use qsort to sort both arrays, then a simple string matcher to compare them. This will have cost O(mnlog(m+n)), as opposed to O(m^2 n^2), awith the current algorithm
You need to split every line you read by fgets (as you did) in to two strings, and pass them to your find_anagram function. You can do that using strtok:
int main()
{
int flag;
char buf[1000];
FILE *ptr_file;
//Check file existence
//Open the file for reading
while (fgets (buf, 1000, ptr_file) != NULL)
{
char *array1 = strtok(buf, "#");
char *array2 = strtok(NULL, "\n");
flag = find_anagram (array1, array2);
//Check flag value to print your message
}
return 0;
}
//put your find_anagram function
Don't forget to #include <string.h> to use strtok().
My code is like a text compressor, reading normal text and turns into numbers, every word has a number. It compiles in DevC++ but does not end, however, it does not compile in Ubuntu 13.10. I'm getting an error like in the title in Ubuntu "undefined reference to `strlwr'", my code is a little long so I am not able to post it here, but one of the error is from here:
//operatinal funcitons here
int main()
{
int i = 0, select;
char filename[50], textword[40], find[20], insert[20], delete[20];
FILE *fp, *fp2, *fp3;
printf("Enter the file name: ");
fflush(stdout);
scanf("%s", filename);
fp = fopen(filename, "r");
fp2 = fopen("text.txt", "w+");
while (fp == NULL)
{
printf("Wrong file name, please enter file name again: ");
fflush(stdout);
scanf("%s", filename);
fp = fopen(filename, "r");
}
while (!feof(fp))
{
while(fscanf(fp, "%s", textword) == 1)
{
strlwr(textword);
//some other logic
}
}
.... //main continues
strlwr() is not standard C function. Probably it's provided by one implementation while the other compiler you use don't.
You can easily implement it yourself:
#include <string.h>
#include<ctype.h>
char *strlwr(char *str)
{
unsigned char *p = (unsigned char *)str;
while (*p) {
*p = tolower((unsigned char)*p);
p++;
}
return str;
}
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char* strlwr(char* );
int main()
{
printf("Please Enter Size Of The String: \n");
int a,b;
scanf("%d",&a);
char* str;
str=(char*)malloc(sizeof(char)*a);
scanf("\n%[^\n]",str);
char* x;
x=strlwr(str);
for(b=0;x[b]!='\0';b++)
{
printf("%c",x[b]);
}
free(str);
return 0;
}
char* strlwr(char* x)
{
int b;
for(b=0;x[b]!='\0';b++)
{
if(x[b]>='A'&&x[b]<='Z')
{
x[b]=x[b]-'A'+'a';
}
}
return x;
}
I've been working on this C programming assignment and I just can't seem to find out why it is not behaving the way I expect it to be behaving. The program is supposed to run, and there are 3 possible options for commands 0, -n, and n, where n is a positive integer.
When I execute the program, and type 0 as the command (which should create a file if one has not already been created) it just loops back to asking me to enter a command.
The commands -n and n go to the line specified by n and seeks to it. n prints line n, whereas -n prints all lines from n onward until it can no longer read from the text file.
Would greatly appreciate it if somebody could give me a hint or two and steer me in the right direction.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#define BUFSIZE 256
#define LINESIZE 1024
int write(FILE *fp);
int grade_validation(int grade);
int id_validation(char studentid[]);
int display(FILE *fp, int cmd);
int display_all(FILE *fp, int cmd);
int main(int argc, char *argv[]) {
if(argc != 2) {
perror("invalid number of args");
return 1;
} else {
FILE *fp;
if((fp = fopen(argv[1], "wb+")) == 0) {
perror("fopen");
return 1;
}
write(fp);
fclose(fp);
}
return 0;
}
int write(FILE* fp) {
int grade;
char studentid[BUFSIZE];
char input[BUFSIZE];
int cmd;
while(1) {
printf("Input 0 to append, n to view, or -n to view all records starting from n.\n");
if(!fgets(input, LINESIZE, stdin)) {
clearerr(stdin);
return 0;
}
if((sscanf(input, "%d", &cmd) == 1)) {
if(cmd == 0) {
if((id_validation(studentid)) != 1 || (grade_validation(&grade) == -1)) {
continue;
}
fprintf(fp, "%s %3d ", studentid, grade);
} else if(cmd > 0) {
display(fp, cmd);
} else if(cmd < 0) {
display_all(fp, cmd);
}
}
}
}
int grade_validation(int grade) {
char input[BUFSIZE];
FILE *fp;
if(grade >= 0 && grade <= 100) {
return 1;
}
if(sscanf(input, "%d", &grade) == 1) {
if((grade_validation(grade)) == 1) {
if(fprintf(fp, "%3d", grade) == 0) {
return 0;
}
printf("Grade recorded successfully.\n");
return 1;
}
}
return 0;
}
int id_validation(char studentid[]) {
char input[BUFSIZE];
FILE *fp;
size_t i = 0;
if(strlen(studentid) == 9) {
for(i = 0; i < 9; i++) {
if(isdigit(studentid[i])) {
return 1;
}
}
}
if(sscanf(input, "%s", studentid) == 1) {
if((id_validation(studentid)) == 1) {
if(fprintf(fp, "%s", studentid) == 0) {
return 0;
}
printf("Student ID recorded successfully.\n");
return 1;
}
}
return 0;
}
int display(FILE *fp, int cmd) {
char studentid[BUFSIZE];
int grade;
if(!fgets(cmd, BUFSIZE, fp)) {
clearerr(stdin);
return 0;
}
fseek(fp, cmd, SEEK_SET);
fprintf(stderr, "%s %3d", studentid, grade);
}
int display_all(FILE *fp, int cmd) {
char studentid[BUFSIZE];
int grade;
if(!fgets(cmd, BUFSIZE, fp)) {
clearerr(stdin);
return 0;
}
fseek(fp, cmd, SEEK_SET);
while((sscanf(studentid, grade, "%s %3d", cmd)) != EOF) {
fprintf(stderr, "%s %3d", studentid, grade);
}
}
You're trying to validate the uninitialized studentid and grade.
Also, you pass &grade to grade_validation, which expects and integer.
This would cause a warning, which should make you figure out something is wrong. Always compile with warnings enabled, and treated as errors (in gcc, -Wall -Werror).