I'm having trouble reading a keyword from file that a user inputs to search for. The first part of the program asks for user input for naming the file. It then asks for sentence input. You can input sentences until you write "END". When you write "END", the appending of sentences to file should stop and the program should ask you for a keyword to search the sentences appended to the newly created textual file. I used 'gets' to ask for a word that will be searched for in the file. The program should find that word in a sentence and print back the whole sentence containing the keyword. The whole code looks like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char fileName[128];
printf("Input your filename (end with .txt):");
gets(fileName);
FILE *filePointer = NULL;
char text1[128];
char word1[128];
filePointer = fopen(fileName, "a");
if(filePointer == NULL)
{
printf("Cannot open file!");
exit(EXIT_FAILURE);
}
else{
printf("Input your sentence: ");
while (fgets(text1, 127, stdin) != NULL && strncmp(text1, "END\n", 5) != 0){
printf("Input your sentence: ");
fprintf(filePointer, "%s", text1);
}
int line_num = 1;
int find_result = 0;
char text2[128];
filePointer = fopen(fileName, "r");
printf("Input keyword you're looking for: ");
gets(word1);
while(fgets(text2, 127, filePointer) != NULL) {
if((strstr(text2, word1)) != NULL) {
printf("A match found on line: %d\n", line_num);
printf("\n%s\n", tekst2);
find_result++;
}
line_num++;
}
if(find_result == 0) {
printf("\nSorry, couldn't find a match.\n");
}
if(filePointer) {
fclose(filePointer);
}
return(0);
}
}
It all works, but the problem is somewhere here:
int line_num = 1;
int find_result = 0;
char text2[128];
filePointer = fopen(fileName, "r");
printf("Input keyword you're looking for: ");
gets(word1);
while(fgets(text2, 127, filePointer) != NULL) {
if((strstr(text2, rijec)) != NULL) {
printf("A match found on line: %d\n", line_num);
printf("\n%s\n", text2);
find_result++;
}
line_num++;
}
I'm new at C programming, so I'm not sure where the flaw is. I know it should work in theory. It doesn't return a result when it clearly should.
You need to fclose() the file after writing, before reopening to read.
if (fclose(filePointer) != 0)
{
fputs("The sky is falling.", stderr);
return 1;
}
filePointer = fopen(fileName, "r");
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 want to write my own code for tail Unix command but I am having a lot of trouble doing that. I am completely new to C language and apparently lost on how to fix my code. I am having number of problems regarding my code:
I am unable to read and print lines from text file in the if statements it is not printing any string from file when I run it don't know why?
Unable to print specific lines in if statement by taking user input as starting line and then printing till the End of File.
I am having trouble figuring out the right solution to my problems and debugging what problems there are in code.
I would really appreciate your help in figuring how to do all the above in my code. If someone can help make changes and get my code to work right.
#include <stdio.h>// for fopen, fscanf, fclose, fprintf
#include <stdlib.h>// for exit
#include <string.h>
int main(int argc, const char * argv[]){
printf("Opening file\n");
char filename[64]; // file attribute
strcpy(filename, argv[1]); //copy string from argv[1] to filename
printf("FILENAME: %s \n", filename);
FILE* fp; // file pointer
int ch, linestotal = 0, user;
char c[10000];
if(argv[2]){ //checking input argv[2]
user = atoi(argv[2]); // char to int
}
fp = fopen( filename, "r"); // file read
if(fp == NULL){ // verify file is opened
printf("Error opening file");
exit(1);
}
while(!feof(fp)) // check end of file
{
ch = fgetc(fp);
if(ch == '\n')
{
linestotal++; //Checking total lines inside file
}
}
printf("Total no. of lines: %d\n", linestotal );
printf("User input: %d\n", user );
printf("**********************\n");
if (!user && linestotal<= 10)
{
while ( (ch = fgetc(fp) ) != EOF)
printf("%c", ch);
fclose(fp);
printf("********************\n");
}if(!user && linestotal>10) { // to print 10 lines
for(int i = (linestotal-10); i <= (linestotal); i++)
{ c[i] = fgetc(fp);
printf("%c", c[i]);
}
fclose(fp);
printf("********************\n");
}if(user && user<linestotal) {
for(int i = (linestotal-user); i <= (linestotal); i++)
{ c[i] = fgetc(fp);
printf("%c", c[i]);
}
fclose(fp);
printf("********************\n");
}if(user && user>linestotal){
while ( (ch = fgetc(fp) ) != EOF)
printf("%c", ch);
fclose(fp);
printf("********************\n");
}else{
printf("Unable to read and print file \n");
}
printf("End of file");
return 0;
}
I am trying to create a function which inserts texts between lines according to the user input. The user has to specify the line number and the index in order to insert his line.
Currently, I have managed to insert the text before the line, but I can't insert it into the line "index".
Does anyone know how to insert according to the index number?
PS. I am still starter at C programming. I know there are too many times that the file is opened and closed!
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
void inserttext(void);
main ()
{
inserttext();
}
void inserttext(void)
{
FILE *file1,*file2;
char *f = malloc(sizeof(char)), *t = malloc(sizeof(char));
int l,i,r,y,n,index,nl=0;
printf("Enter a text file name: ");
scanf("%s",f);
if (access(f,F_OK)!=-1)//if the text file exists
{
file1=fopen(f, "r+");
file2=fopen("f2.txt", "w+");
printf("\nThe file before editing:\n\n");
while((n=fgetc(file1))!=EOF)// to show the contents of the file before the edit
{
putchar(n);
}
fclose(file1);
fclose(file2);
if(access(f,W_OK)!=-1)//if the file has the write permission
{
file1=fopen(f, "r+");
file2=fopen("f2.txt", "w+");
printf("\n\nPlease enter your text: \n");
scanf(" %[^\n]s ",t);
printf("Specify the line number where you want to insert: ");
scanf("%d", &l);
printf("\nindex:\n");
scanf("%d", &index);
while((r=fgetc(file1))!=EOF)//copying file1 contents into file2 contents
{
fputc(r,file2);
if(r == '\n' && ++nl == l){
fprintf(file2, "%s ", t);//adding the inserted text
}
}
fclose(file1);
fclose(file2);
file1=fopen(f, "w+");
file2=fopen("f2.txt", "r");
while((y=fgetc(file2))!=EOF){
fputc(y,file1);
}
fclose(file2);
fclose(file1);
remove("f2.txt");
file1=fopen(f, "r");
printf("\n");
while((i=fgetc(file1))!=EOF)//showing the result after inserting
{
putchar(i);
}
fclose(file1);
free(f);
free(t);
}
else{
printf("\n%s text file does not have the Write Permission!", f);
free(f);
free(t);
return;
}
}else{
printf("file doesn't exits!\n");
}
}
This uses ftell() and fseek() to save the file position at the start of the selected line, read the length of the line and return to the start of the line.
The user is prompted to input an index into the line less than the line length.
I did get a segmentation fault with the original malloc's for *t and *f. I tried some longer inputs, so this allocates 100 characters to each pointer.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
void inserttext(void);
int main ()
{
inserttext();
return 0;
}
void inserttext(void)
{
FILE *file1,*file2;
char *f = malloc(100), *t = malloc(100);
int l,i,r,y,n,index,nl=0;
int linelength = 0;;
long offset = 0;
printf("Enter a text file name: ");
scanf("%99s",f);
if (access(f,F_OK)!=-1)//if the text file exists
{
file1=fopen(f, "r+");
file2=fopen("f2.txt", "w+");
printf("\nThe file before editing:\n\n");
while((n=fgetc(file1))!=EOF)// to show the contents of the file before the edit
{
putchar(n);
}
fclose(file1);
fclose(file2);
if(access(f,W_OK)!=-1)//if the file has the write permission
{
file1=fopen(f, "r+");
file2=fopen("f2.txt", "w+");
printf("\n\nPlease enter your text: \n");
scanf(" %99[^\n]",t);
printf("Specify the line number where you want to insert: ");
scanf("%d", &l);
while((r=fgetc(file1))!=EOF)//copying file1 contents into file2 contents
{
fputc(r,file2);
if(r == '\n' && ++nl == l){
offset = ftell ( file1);//save location in file
while ( ( r = fgetc ( file1)) != '\n' && r != EOF) {
linelength++;//count characters in line
}
fseek ( file1, offset, SEEK_SET);//seek back to start of line
//get index where to insert text
do {
printf("\nindex(less than %d):\n", linelength);
if ( ( scanf("%d", &index)) != 1) {
scanf ( "%*[^\n]");//input not an integer. clear buffer
index = linelength;
}
} while ( index >= linelength || index < 0);
while ( index) {
r = fgetc ( file1);
fputc(r,file2);
index--;
}
fprintf(file2, "%s ", t);//adding the inserted text
}
}
printf("\nDONE:\n");
fclose(file1);
fclose(file2);
file1=fopen(f, "w+");
file2=fopen("f2.txt", "r");
while((y=fgetc(file2))!=EOF){
fputc(y,file1);
}
fclose(file2);
fclose(file1);
remove("f2.txt");
file1=fopen(f, "r");
printf("\n");
while((i=fgetc(file1))!=EOF)//showing the result after inserting
{
putchar(i);
}
fclose(file1);
free(f);
free(t);
}
else{
printf("\n%s text file does not have the Write Permission!", f);
free(f);
free(t);
return;
}
}else{
printf("file doesn't exits!\n");
}
}
I want to write code were the user is asked to write the name of a file. Then I want to analyze the file's content for a symbol, let's say 'e'.
My problem is that I don't know how to start analyzing the file the correct way so that the content can be checked.
int main() {
char c[1000], file_name[1000];
int i;
int s = 0;
FILE *fp;
printf("Enter the name of file you wish to see\n");
gets(file_name);
if ((fp = fopen(file_name, "r")) == NULL){
printf("Error! opening file");
exit(1);
}
if (fp) {
while (fscanf(fp, "%s", c) != EOF) {
printf("%s", c);
}
fclose(fp);
for (i = 0; c[i] != '\0'; ++i) {
puts(c);
if (c[i] == 'e') {
++s;
}
}
printf("\nWhite spaces: %d", s);
_getche();
return 0;
}
}
char line[512]; /*To fetch a line from file maximum of 512 char*/
rewind(fp);
memset(line,0,sizeof(line)); /*Initialize to NULL*/
while ( fgets(line, 512, fp ) && fp !=EOF)
{
/*Suppose u want to analyze string "WELL_DONE" in this fetched line.*/
if(strstr(line,"WELL_DONE")!=NULL)
{
printf("\nFOUND KEYWOD!!\n");
}
memset(line,0,sizeof(line)); /*Initialize to null to fetch again*/
}
If its just a symbol you're looking for, or a char, you can simply use getc() :
int c;
....
if (fp) {
while ((c = getc(fp)) != EOF) {
if (c == 'e') {
// Do what you need
}
}
Or, alternatively, if it's a word you're looking for, fscanf() will do the job:
int c;
char symb[100];
char symbToFind[] = "watever"; // This is the word you're looking for
....
while ((c = fscanf(fp, %s, symb)) != EOF) {
if (strcmp(symb, symbToFind) == 0) { // strcmp will compare every word in the file
// do whatever // to symbToFind
}
}
These alternatives will allow you to search every char or string in the file, without having to save them as an array.