How can I compare user input to string stored into file? - c

I gotta write a file-handing code which will compare the string received from the user to a string of char stored into a file in C. I've trying since yesterday. I have no clue on how to do that. I tried many things, but nothing seems to work.
//
// 2.c
// IFTM Exercises
//
// Created by Lelre Ferreira on 10/27/19.
// Copyright © 2019 Lelre Ferreira. All rights reserved.
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (int argc, const char * argv[]){
FILE *file = fopen("file.txt", "w");
char text[] = "hi hi hi hi hi hi"; //string to be allocated into the file
char c, userInput[] = "hi"; // simulates the user input
int i = 0, count = 0;
if (file == NULL) {
printf("Failure to create file.\n");
exit(1);
} else {
for (i = 0; i < strlen(text); i++) {
printf("Inserting: [%c]\n", text[i]);
fputc(text[i], file);
}
printf("All done.\n");
}
fclose(file);
fopen("file.txt", "r");
while ((c = fgetc(file) != EOF)){
fscanf(file, "%s", text);
if (strcmp(userInput, text) == 0) {
count++;
}
}
fclose(file);
printf("Many times present: %d\n", count);
return 0;
}
My problem is... the space between every word of the string in the file, because I have to check if there's another word starting, for instance... (Hi Hi)... I thought about using something like this in my code but I did not work as well.
while ((c = fgetc(file) != EOF)){ // While the end of the file does not happen keep running.
if ((c = fgetc(file) != ' ')) { //If an blank space is found... I does not make any sense actually. I'm desesperated.
strcmp(userInput, text){
count++
}
}
}

while ((c = fgetc(file) != EOF)){
if ((c = fgetc(file) != ' ')) {
strcmp(userInput, text){
count++
}
}
}
There are three major problems here.
First, c = fgetc(file) != EOF is the same as c = (fgetc(file) != EOF) which obviously is not what you want. It should be (c = fgetc(file)) != EOF
Second, the above statement has (provided you did not get an EOF) actually read a character. So the if statement should be if(c != ' ')
Third, c needs to be declared as an int

Related

running the program doesn't print the second printf statement

whenever I run the program the second print statement isn't printing. I tried using a function but I'm new to C and don't really understand anything. I've also attached my activity as I'm not sure how to do the other things on it.activity photo
#include <stdio.h>
#include <string.h>
#define LINE_LENGTH 1000
int main(int argc, char **argv)
{
FILE *input_file = fopen("cstest.c", "r");
char line [LINE_LENGTH];
//while loop to ger
while (fgets(line, LINE_LENGTH, input_file) != NULL)
{
int ch = 0;//ch is the cast
int lines = 0;//start with one because
if (input_file == NULL)
return 0;
while (!feof(input_file))
{
ch = fgetc(input_file);
if (ch == '\n')
{
lines++;
}
}//end while
printf("lines: %d\n", lines);
}//end while loop
while (fgets(line, LINE_LENGTH, input_file) != NULL)
{
int ch = 0;//ch is the cast
int lines = 0;//start with one because
if (input_file == NULL)
return 0;
while (!feof(input_file))
{
int characters = 0;
char c;
for (c = getc(input_file); c != EOF; c = getc(input_file))
// Increment count for this character
characters = characters + 1;
printf("characters: %d\n", characters);
fclose(input_file);
}
}
}

I need to fix this two problems in the program. Based on the inputs, I need a fix on the code to produce the desired output

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
void handle(FILE *np)// this is to handle newline characters
{
putc('\n', np);
}
/* skip a C multi-line comment, return the last byte read or EOF */
int m_cmnt(FILE *fp, int *lineno_p) {
FILE *np = stdout;
int prev, ch, replacement = ' ';
for (prev = 0; (ch = getc(fp)) != EOF; prev = ch) {
if (prev == '\\' && ch == 'n') {
replacement = '\n';
++*lineno_p;
}
if (prev == '*' && ch == '/')
return replacement;
}
return EOF;
}
int main(int argc, char *argv[]) {
FILE *fp = stdin, *np = stdout;
int ch,prev;
bool String = 0;
const char *filename = "<stdin>";
int lineno = 1;
fp = fopen(filename, "r");
np = fopen(argv[2], "w");
if (argc > 1) {
if ((fp = fopen(filename = argv[1], "r")) == NULL) {
fprintf(stderr, "Cannot open input file %s: \n",
filename);
exit(EXIT_FAILURE);
}
}
if (argc > 2) {
if ((np = fopen(argv[2], "w")) == NULL) {
fprintf(stderr, "Cannot open output file %s: \n",
argv[2]);
exit(EXIT_FAILURE);
}
}
while ((ch = getc(fp)) != EOF) {
if (ch == '\n')
lineno++;
/* file pointer currently not inside a string */
if (!String) {
if (ch == '/') {
ch = getc(fp);
if (ch == '\n')
lineno++;
if (ch == '*') {
int startline = lineno;
ch = m_cmnt(fp, &lineno);
if (ch == EOF) {
fprintf(stderr, "%s:%d: error: unterminated comment started on line %d\n",
filename, lineno, startline);
exit(EXIT_FAILURE);
break;
}
putc(ch, np);
} else {
putc('/', np);
putc(ch, np);
}
}
else if ( ch=='\\')/*to handle newline character*/
{
prev=ch ;
ch= getc(fp) ;
switch(ch)
{
case 'n' :
handle(np);
break ;
/*default :
putc(prev , np) ;
putc(ch , np) ;
break ;*/
}
}
else {
putc(ch, np);
}
} else {
putc(ch, np);
}
if (ch == '"' || ch == '\'')
String = !String;
}
fclose(fp);
fclose(np);
//remove(arr[1]);
//rename("temp.txt", arr[1]);
return EXIT_SUCCESS;
}
I have been working on this project for almost more than a week now. I have asked many questions on this site to help me get the desired result.The basics of this program is to remove multiline comments from source file and write the rest to some output file. It also need to to ignore any thing that is inside a string literal or character literal(like escaped characters). Now I have come to finalize it but I still need to achieve this two outputs shown below
INPUT1 = //*SOMECOMMENT*/
OUTPUT1 = /
INPUT2 = "this \"test"/*test*/
OUTOUT2 = "this \"test"
The current(erroneous) output is shown below
INPUT1 = //*SOMECOMMENT*/
OUTPUT1 = //*SOMECOMMENT*/ This is wrong.
INPUT2 = "this \"test"/*test*/
OUTOUT2 = "this \"test"/*test*/ This is also wrong.
The program don't work for the case where a comment comes after a forward slash(/) and the second failure of the program is it don't ignore escape character inside a string or character literal. I need a fix on this two problems please.
If your problem is that you want to read an input stream of characters, divide that stream into tokens, and then emit only a subset of those tokens, I think Lex is exactly the tool you're looking for.
If I understand your comment correctly, the file you're trying to read in and transform is itself C code. So you will need to build up a Lex definition of the C language rules.
A quick search turned up this Lex specification of the ANSI C grammar. I cannot vouch for its accuracy or speak to its licensing. At first glance it seems to only support C89. But it is probably enough to point you in the right direction.

Replacing a line in a text file with a string

I am learning file handling in C. I wrote code to replace a line in a file with a string input by the user. The replacing progress itself works great, but somehow the first line is always empty and I am able to understand what goes wrong.
Additionally I have some additional questions about file handling itself and about tracking down the mistakes in my code. I understand by now that I should have used perror() and errno. This will be the next thing I will read on.
Why shouldn't I use "w+" establishing the file stream? (A user on here told me to better not use it, unfortunately I couldn't get an explanation)
I tried to use gdb to find the mistake, but when I display my fileStored array I get only numbers, since its obviously an int array, how could I improve the displaying of the variable
What would be a good approach in gdb to track the mistake down I made in the code?
The code:
#include <stdio.h>
#include <stdlib.h>
#define MAXLENGTH 100
int main(int argc, char *argv[]){
FILE *fileRead;
char fileName[MAXLENGTH],newLine[MAXLENGTH];
int fileStored[MAXLENGTH][MAXLENGTH];
short lineNumber, lines = 0;
int readChar;
printf("Input the filename to be opened:");
int i = 0;
while((fileName[i] = getchar()) != '\n' && fileName[i] != EOF && i < MAXLENGTH){
i++;
}
fileName[i] = '\0';
if((fileRead = fopen(fileName, "r")) == NULL){
printf("Error: File not found!\n");
return EXIT_FAILURE;
}
i = 0;
while((readChar = fgetc(fileRead)) != EOF){
if(readChar == '\n'){
fileStored[lines][i] = readChar;
i = 0;
lines++;
}
fileStored[lines][i] = readChar;
i++;
}
fclose(fileRead);
fileRead = fopen(fileName, "w");
printf("Input the content of the new line:");
i = 0;
while((newLine[i] = getchar()) != '\n' && newLine[i] != EOF && i < MAXLENGTH){
i++;
}
newLine[i] = '\0';
printf("There are %d lines.\nInput the line number you want to replace:",lines);
scanf("%d",&lineNumber);
if((lineNumber > lines) || (lineNumber <=0)){
printf("Error: Line does not exist!");
return EXIT_FAILURE;
}
int j = 0;
for(i = 0; i < lines; i++){
if(i == lineNumber-1){
fprintf(fileRead,"\n%s",newLine);
continue;
}
do{
fputc(fileStored[i][j],fileRead);
j++;
}while(fileStored[i][j] != '\n');
j = 0;
}
fclose(fileRead);
return EXIT_SUCCESS;
}

Implementing fgetc; trying to read word by word

I am trying to read word by word, and below is the logic that I have adopted. This is reading in the words fine, except when it gets to the last word in a line, in which it stores the last word of the current file AND the 1st word of the next new line. Could somebody tell me how I can get this to work?
int c;
int i =0;
char line[1000]
do{
c = fgetc(fp);
if( c != ' '){
printf("%c", c);
line[i++] = c;
}else if((c == '\n')){
//this is where It should do nothing
}else{
line[i] = '\0';
printf("\\0 reached\n");//meaning end of one word has been reached
strcpy(wordArr[counter++].word, line);//copy that word that's in line[xxx] to the struct's .word Char array
i=0;//reset the line's counter
}//if loop end
} while(c != EOF);//do-while end
fp is a file pointer.
HI BABY TYPE MAYBE
TODAY HELLO CAR
HELLO ZEBRA LION DON
TYPE BABY
I am getting (w/o quotes)
"HI"
"BABY"
"TYPE"
"MAYBE
TODAY"
Look at this:
if(c != ' ') {
// ...
} else if(c == '\n') {
// WILL NEVER BE REACHED
}
If c == '\n', then c != ' ' is also true, which means the second block will be skipped, and the first block will run for all '\n' characters, (i.e. they will be printed).
Other answers about line endings are wrong. C FILE *s not opened in binary mode will take care of EOL for you. If you have a file from DOS and you read it on Unix it might create problems, but I doubt that's your problem here, and if it was handling it could be a little more complicated than the answers here show. But you can cross that bridge when you reach it.
The encoding of the line terminating character is different from one operating system to another. In Linux, it is simply '\n', while in Windows and DOS it is '\r\n'. So, depending on your target OS, you may need to change your statement in something like:
if((c == '\r' || (c == '\n'))
{
//...
}
EDIT: after looking closely, I think that what you're doing wrong is that the first if statement is true even when you read the \n, so you should handle it this way:
if((c != ' ') && (c != '\n')){
printf("%c", c);
line[i++] = c;
}
else if((c == '\n') || (c == '\r')){
//this is where It should do nothing
}
else{
//...
}
Try this;
if((c == '\n') || (c == '\r'){
change
if( c != ' ')
to
if( c != ' '&&c!='\n')
this should fix the problem
This works for me (on Linux):
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int
main(int argc, char **argv)
{
char c;
size_t i = 0;
FILE *file = NULL;
char buffer[BUFSIZ];
int status = EXIT_SUCCESS;
if (argc < 2) {
fprintf(stderr, "%s <FILE>\n", argv[0]);
goto error;
}
file = fopen(argv[1], "r");
if (!file) {
fprintf(stderr, "%s: %s: %s\n", argv[0], argv[1],
strerror(errno));
goto error;
}
while (EOF != (c = fgetc(file))) {
if (BUFSIZ == i) {
fprintf(stderr, "%s: D'oh! Write a program that "
"doesn't use static buffers\n",
argv[0]);
goto error;
}
if (' ' == c || '\n' == c) {
buffer[i++] = '\0';
fprintf(stdout, "%s\n", buffer);
i = 0;
} else if ('\r' == c) {
/* ignore */
} else {
buffer[i++] = c;
}
}
exit:
if (file) {
fclose(file);
}
return status;
error:
status = EXIT_FAILURE;
goto exit;
}

How Can I Get getc() to Return a Character Besides a Smiley Face?

I am trying to write a simple 'cat' clone in C. I'm running Windows 7 and using the MinGW compiler. However, whenever I run the program, it returns the text file but with each character replaced with a '☺' character. Thank you in advance.
#include <stdio.h>
int main(int argc, char *argv[])
{
int i;
FILE *fp;
int c;
for(i = 1; i < argc; i++)
{
fp = fopen(argv[i], "r");
if(fp == NULL)
{
fprintf(stderr, "cat: can't open %s\n", argv[i]);
continue;
}
while((c = getc(fp) != EOF))
{
putchar(c);
}
fclose(fp);
}
return 0;
}
Since relational equal test (!=) has greater precedence than assignment (=) you'll just store 1 in c at every iteration. Put otherwise, one of the brackets is in the wrong place.
while((c = getc(fp) != EOF))
^
{
putchar(c);
}
Right:
while((c = getc(fp)) != EOF)
{
putchar(c);
}

Resources