I want to write a program to print all words containing a letter ("D" for example) in a text file.
This is what I came up with, but it does not work.
I get the core dumped error.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFER_SIZE 1000
int findWord(FILE *file , const char *letter);
void main()
{
FILE *file;
char path[100];
char letter[1];
printf("Enter file path: ");
scanf("%s", path);
printf("Enter letter to search in file: ");
scanf("%s", letter);
file = fopen(path, 'r');
if (file == NULL)
{
printf("Unable to open file.\n");
printf("Please check you have read/write priveleges.\n");
exit(EXIT_FAILURE);
}
findWord(file, letter);
fclose(file);
return 0;
}
int findWord(FILE *file, const char *letter)
{
char str[BUFFER_SIZE];
while ((fgets(str, BUFFER_SIZE, file)) != NULL)
{
if (str == letter)
{
printf(letter);
}
}
}
Edited your code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define BUFFER_SIZE 1000
int findWord(FILE *file , const char letter);
int main()
{
FILE *file;
char path[100];
char letter;
// const char *fpath = "/home/kozmotronik/Belgeler/karalama.txt";
printf("Enter file path: ");
// fgets(path, sizeof(path), stdin);
// printf("Entered file path: %s\n", path);
scanf("%s", path);
// flushes the standard input
// (clears the input buffer)
// If we don't do this we cannot get the letter from the input buffer
while ((getchar()) != '\n');
printf("Enter letter to search in file: ");
letter = getchar();
// Validity check
if(letter < '0' || letter > 'z') {
printf("Entered character is not valid\n");
exit(EXIT_FAILURE);
}
file = fopen(path, "r");
if (file == NULL)
{
printf("Unable to open file.\n");
printf("Please check you have read/write priveleges.\n");
exit(EXIT_FAILURE);
}
findWord(file, letter);
fclose(file);
return 0;
}
int findWord(FILE *file, const char letter)
{
char str[BUFFER_SIZE];
while ((fgets(str, BUFFER_SIZE, file)) != NULL)
{
printf("Looking for '%c' in %s\n", letter, str);
char *c = strchr(str, (int)letter);
if (c != NULL)
{
printf("'%c' found in %s\n", *c, str);
}
}
return 0;
}
In the same directory of the source code, created afile.txt file and entered the file name. Here is the output for the program:
Enter file path: afile.txt
Enter letter to search in file: e
Looking for 'e' in This file contains some text.
'e' found in This file contains some text.
Looking for 'e' in This file is used for testing purposes.
'e' found in This file is used for testing purposes.
Looking for 'e' in This file must be read only.
'e' found in This file must be read only.
And here is the afile.txt file content:
This file contains some text.
This file is used for testing purposes.
This file must be read only.
You are encouraged to split a line of string into the words and search the letter in the word list.
Here is an example.
#include <stdio.h>
#include <stdlib.h>
#include <mem.h>
#define BUFFER_SIZE 1000
void findWord(FILE *file , const char *letter);
int main()
{
FILE *file;
char path[100];
char letter[2];
printf("Enter file path: ");
scanf("%s", path);
printf("Enter letter to search in file:");
scanf("%s", letter);
file = fopen(path, "r");
if (file == NULL)
{
printf("Unable to open file.\n");
printf("Please check you have read/write priveleges.\n");
exit(EXIT_FAILURE);
}
findWord(file, letter);
fclose(file);
return 0;
}
void findWord(FILE *file, const char *letter)
{
char str[BUFFER_SIZE];
do
{
fscanf(file, "%s", str);
if(strchr(str, letter[0]) > 0){
printf("%s\n", str);
}
}while (fgetc(file) != EOF);
}
Related
I'm trying to copy words from one file to another, but the words must begin with the given letter. It's working but doesn't copy every word that matches.
#include <stdio.h>
int main() {
FILE *f = fopen("words.txt", "r");
FILE *f2 = fopen("words_copy.txt", "a+");
char usr;
printf("enter letter: ");
scanf("%c", &usr);
char buffer[255];
char ch, ch2;
while ((ch = fgetc(f)) != EOF) {
ch2 = fgetc(f);
if (ch2 == usr && ch == '\n') {
fputc(ch2, f2);
fgets(buffer, sizeof(buffer), f);
fputs(buffer, f2);
}
}
return 0;
}
Words.txt contains:
adorable aesthetic alluring angelic appealing arresting attractive
blooming charismatic charming cherubic chocolate-box classy contagious
cute dazzling debonair decorative delectable delicate distinguished
enchanting enticing eye-catching glamorous glossy good-looking
gorgeous infectious lovely lush magnetic magnificent majestic melting
mesmerizing noble picturesque poetic prepossessing shimmering striking
stunning winsome
every word is in next line,
when I'm running the program and giving the letter m words_copy.txt contains only:
magnificent melting
How to fix to copy every word with matching letter?
The test in the loop is incorrect: you check the first letter after a newline and output the line if there is a match. With this logic:
you cannot match the first word in the file
you only match words starting with usr
and the word following a match is ignored
Furthermore, you ch and ch2 should be defined with type int to match EOF reliably, you should test for fopen failure and close the files after use.
You should use a simpler approach:
read a word
test if it contains the letter
output the word if it matches
Here is a modified version:
#include <ctype.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char usr;
char buffer[256];
int ch = 0;
size_t pos;
FILE *f = fopen("words.txt", "r");
if (f == NULL) {
fprintf(stderr, "cannot open words.txt: %s\n", strerror(errno));
return 1;
}
FILE *f2 = fopen("words_copy.txt", "a+");
if (f2 == NULL) {
fprintf(stderr, "cannot open words_copy.txt: %s\n", strerror(errno));
fclose(f);
return 1;
}
printf("enter letter: ");
if (scanf(" %c", &usr) != 1) {
fprintf(stderr, "missing input\n");
fclose(f);
fclose(f2);
return 1;
}
while (ch != EOF) {
pos = 0;
/* read a word, stop at whitespace and end of file */
while ((ch = fgetc(f)) != EOF && !isspace(ch)) {
if (pos + 1 < sizeof(buffer))
buffer[pos++] = (char)ch;
}
buffer[pos] = '\0';
/* test for a match */
if (strchr(buffer, usr)) {
/* output matching word */
fprintf(f2, "%s\n", buffer);
}
}
fclose(f);
fclose(f2);
return 0;
}
I want to give input as line number and get output as the corresponding text for that line number in a text file.
Sample text file:
Hi this is Stefen
Hi How are you
Example input:
Enter the line number:2
Expected Output:
Hi How are you
My program is:
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *fp;
fp = fopen("sample.txt", "r");
if (fp == NULL) {
perror("Unable to open the file\n");
exit(1);
}
char buf[256];
while (fgets(buf, sizeof(buf), fp) != NULL) {
printf("%s\n", buf);
print("~~~~\n");
}
fclose(fp);
return 0;
}
Output I got:(The entire file with the separator ~~~~ below each line)
Hi this is Stefen
~~~~
Hi How are you
~~~~
Can anyone please tell me how to do this?
As pmg suggests, would you please try the following:
#include <stdio.h>
#include <stdlib.h>
#define INFILE "sample.txt"
int main()
{
FILE *fp;
char buf[BUFSIZ];
int count = 0, n;
fp = fopen(INFILE, "r");
if (fp == NULL) {
perror(INFILE);
exit(1);
}
printf("Enter the line number: ");
fgets(buf, sizeof buf, stdin);
n = (int)strtol(buf, (char **)NULL, 10);
while (fgets(buf, sizeof buf , fp) != NULL){
if (++count == n) {
printf("%s", buf);
break;
}
}
fclose(fp);
return EXIT_SUCCESS;
}
Best to use a second file
check if you're at \n that means new line and increment a variable like "line"
printf(" \n Enter line number of the line to be deleted:");
scanf("%d", &delete_line);
//open new file in write mode
ptr2 = fopen("c:\\CTEMP\\newfile.txt", "w");
if(ptr2==NULL)
printf("second error opening newfile");
while (!feof(ptr1))
{
ch = fgetc(ptr1);
if (ch == '\n')
{
temp++;
}
//except the line to be deleted
if (temp != delete_line)
{
//copy all lines in file newfile.c
fputc(ch, ptr2);
}
}
fclose(ptr1);
fclose(ptr2);
"detele_line" variable is for the user to inter.
The easiest way is using array to save the lines, then print the certain line.
#include <stdio.h>
#define M 10010
#define N 256
char buf[M][N];
int main(){
FILE *file;
char fileName[50] = "sample.txt";
file = fopen(fileName, "r");
if(file == NULL)
return 1;
int n = 0;
while(fgets(buf[n], N, file) != NULL){
n++;
}
fclose(file);
int i, x;
printf("Example input:\nEnter the line number:");
scanf("%d", &x);
printf("Expected Output:\n%s", buf[x-1]);
return 0;
}
I am trying pass a char array to a function. The array is initialized by the user's input. The input is a file name that will be opened and read in the function to determine how many of the integers in the file match the user's target integer (the file only contains integers). I am getting the user's input with fgets(). But when I pass the char array with the user's file name to the function, I get a NULL file pointer, even though the file I've tried to pass is in the same directory as my executable file.
Also, I am trying to get two more file name inputs from the user for another function. The first file is a source file, and the second file is the destination file where the contents of the first file will be copied to. I'm using fgets() for this as well, but my output that is asking the user for the second file name is being read by the first fgets() that is trying to read the first file name.
Here is my code:
#include <stdio.h>
#include <stdlib.h>
int countOccurrences (const char* filename, const int target);
int copyFile(const char* src_file, const char* dest_file);
main()
{
printf("**********countOccurrences Test**********\n");
char buffer[15];
int userTarget;
printf("Enter input file name: ");
fgets(buffer, 15, stdin);
printf("Enter target: ");
scanf("%d", &userTarget);
int count = countOccurrences(buffer, userTarget);
printf("Occurrences of %d in \"%s\": %d\n", userTarget, buffer, count);
printf("\n**********copyFile Test**********\n");
char source[15];
char destination[15];
printf("Enter source file name: ");
fgets(source, 15, stdin);
printf("\nEnter destination file name: ");
fgets(destination, 15, stdin);
copyFile(source, destination);
return 0;
}
int countOccurrences (const char* filename, const int target)
{
FILE * numFile;
numFile = fopen(filename, "r");
if(numFile == NULL)
{
printf("Error opening file.\n");
exit(0);
}
int currentNum;
int targetCount = 0;
while(!feof(numFile))
{
fscanf(numFile, "%d", ¤tNum);
if(currentNum == target)
{
targetCount++;
}
}
fclose(numFile);
return targetCount;
}
int copyFile(const char* src_file, const char* dest_file)
{
FILE *source, *destination;
char c;
source = fopen(src_file, "r");
destination = fopen(dest_file, "w");
if((source == NULL) || (destination == NULL))
{
printf("Error opening file.\n");
return 0;
}
while(!feof(source))
{
c = fgetc(source);
fputc(c, destination);
}
fclose(source);
fclose(destination);
return 0;
}
The problem statement : a C program to count the number of times a character appears in the File. character is considered Case insensitive.
I have converted both the input character and character from the file to upper case so that none of the occurrence of the character goes uncounted. but when am executing this on an online editor am getting the result as "wrong answer" the editor isn`t accepting this code. what is the mistake in this code??
#include<stdio.h>
#include<ctype.h>
#include<stdlib.h>
int main
{
FILE *fp;
char filename[20];
char character;
char compare;
int to_upper1;
int to_upper2;
int count=0;
printf("\nEnter the file name");
scanf("%s", filename);
fp = fopen(filename,"r");
if(fp == NULL)
{
exit(-1);
}
printf("\nEnter the character to be counted");
scanf("%c", &character);
to_upper1 = toupper(character);
while((compare = fgets(fp)) != EOF)
{
to_upper2 = toupper(compare);
if(to_upper1 == to_upper2)
count++;
}
printf("\nFile \'%s\' has %d instances of letter \'%c\'", filename, count, character);
return 0;
}
I found a few errors in your code, and made a few small tweaks. The errors are - not eating the "whitespace" before the character input, using fgets() instead of fgetc(), using escape characters before the ' symbols in the output text.
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
int main(void) // added arg for compilability
{
FILE *fp;
char filename[20];
char character;
int compare; // correct type for fgetc and toupper
int to_upper1;
int to_upper2;
int count=0;
printf("Enter the file name: ");
scanf("%19s", filename); // restrict length
fp = fopen(filename,"r");
if(fp == NULL)
{
printf ("Cannot open file '%s'\n", filename);
exit(-1);
}
printf("\nEnter the character to be counted: ");
scanf(" %c", &character); // filter out whitespace
to_upper1 = toupper((int)character);
while((compare = fgetc(fp)) != EOF) // changed from fgets()
{
to_upper2 = toupper(compare);
if(to_upper1 == to_upper2)
count++;
}
fclose(fp); // remember to close file!
printf("File '%s' has %d instances of letter '%c'", filename, count, character);
return 0;
}
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
int main()
{
FILE *fptr;
int d=0;
char c;
char ch,ck;
char b[100];
printf("Enter the file name\n");
scanf("%19s",b);
fptr=fopen(b,"r");
printf("Enter the character to be counted\n");
scanf(" %c",&c);
c=toupper(c);
if(fptr==NULL)
{
exit(-1);
}
while((ck=fgetc(fptr))!=EOF)
{
ch=toupper(ck);
if(c==ch||c==ck)
++d;
}
fclose(fptr);
printf("File '%s' has %d instances of letter '%c'.",b,d,c);
return(0);
}
I am new to programming and have a few questions as to how to implement this idea.
I am looking to have a user enter their name/string of digits and if their name is on a list, to then execute a string of commands. I am not to sure how to impliment this, but with some gogle-ing I was able to come up with this code:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char userName[10];
printf("\n\n\n\nPlease enter your name: ");
scanf_s("%s",userName); // userName should be verified/found inside the results.dat file
FILE *fp;
fp = fopen("results.dat", "r");
if (fp == NULL) {
printf("I couldn't open results.dat for writing.\n");
exit(0);
}
if (fp == John) {
//Dispence squence of pills for John
}
if (fp == Mary) {
//Dispence squence of pills for Mary
}
return 0;
}
I do not think I am using the if statement correctly. how can I do something like:
if (content in fp == john, execute/call another function)
Thanks in advance!
Try this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char userName[10];
char names[20];
printf("\n\n\n\nPlease enter your name: ");
scanf("%s",userName); // userName should be verified/found inside the results.dat file
FILE *fp;
fp = fopen("results.dat", "r");
if (fp == NULL) {
printf("I couldn't open results.dat for writing.\n");
exit(0);
}
while(fgets(names, 20, fp)) // fgets reads a line from the file
{
names[strlen(names)-1] = '\0'; // but it leaves the newline character "\n" , so the strings won't match
if(strcmp(names, userName) == 0) // if the value returned by strcmp is zero then string match
{
printf("Match found\n");
}
}
return 0;
}
fopen simply opens a file for reading and/or writing, to read the actual content of the file you need to use functions such as fgets, fscanf and so on.
Short example
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char* argv[])
{
char name[64];
char buffer[64];
printf ("Please enter your name: ");
file = fopen ("results.dat", "rw");
if (!file) {
printf ("Results.dat could not be opened.\n");
exit(-1);
}
if ( fgets (buffer, 64, file)) {
if (strcmp (buffer, "john")) {
printf ("Contents of file is john\n");
}
}
return 0;
}