The following code reads from a file the occurrences of the digit 1. My question is how could such an occurrence be replaced with another number (say '4') and written back again in the file. The while loop will be continued with?
int next;
FILE *f;
if (!(f=fopen("C:\\Test\\Sign.txt", "rt")))
{
printf("File not existing\n");
}
else{
while((next=='1')!=EOF)
The proper solution for that [including the initial one] would be:
#include <stdio.h>
#include <conio.h>
int f(FILE *);
int main(){
int num=0, next;
FILE *f;
if (!(f=fopen("C:\\Test\\Sign.txt", "rt")))
{
printf("File not existing\n");
}
else{
for(;;){
if((next=fgetc(f))== EOF) break;
if (next == '1') num++;}
}
printf("Found occurrences of digit 1 are %d\n", num);
getch();
}
The for loop counts the occurrences of ones[in this case] whenever it passes through the number with fgetc assigned to the value of next which is 1.
Related
I'm trying to write a program that asks for input of the name of a file and a char to be counted inside the file. But whenever I input the proper name of a file (like, "file.txt") it jumps right to the end of the program with a output like this:
"Name of the file: file.txt
Character to be counted:
The char occurs 0 times in the file "
...but I couldn't even type the char to be counted.
I know it's not an issue with the name of the file, because if I put the wrong name, it goes for the output I programmed for.
Would anyone care to explain me what's happening?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
char filename[128];
printf("Name of the file: ");
scanf("%s", filename);
FILE * test = fopen(filename, "r");
if (test == NULL) {
printf("Error!!\n");
exit(1);
}
char inpt;
printf("Character to be counted:\n");
scanf("%c", &inpt); //gets the character to be counted
int count = 0;
char search = fgetc(test);
while(search != EOF) {
if (search == inpt) count++;
search = fgetc(test);
}
printf("The char occurs %d times in the file\n", count);
return 0;
}
How do I write a C program to enter a number from the keyboard and store it in a text file called number.dat. If the number exists in the file, display an error message. Program should allow to input numbers until the user inputs -99.
I tried this question, but I could not find how to check whether the integer already exists in the file.
This is my C code answer:
#include <stdio.h>
int main(void) {
int num;
FILE *xPtr;
xPtr = fopen("number.dat", "a");
while (num = -99) {
printf("Enter a number : ");
scanf("%d", &num);
if (num == -99)
break;
fprintf(xPtr, "%d\n", num);
}
return 0;
}
I could not find how to check whether an integer already exists in the file.
Can you please give me a solution for this matter?
There are a few things that could be improved. First of all, your while loop is using an assignment operator for the conditional expression:
while(num = -99)
Instead of assigning it to 99 at the beginning of the loop each time, you could do this:
while(num != -99)
Since you want the block inside of the loop to execute when num is not equal to -99. I would also convert it to a do-while loop, since you are not assigning num before you enter the loop the first time. When you are in the loop, you should be opening an closing the file so it can keep track of any numbers you add. In order to check your file you will need to read AND append, it is now currently set to only append. To read and append you will do the following:
xPtr = fopen("number.dat", "a+");
It might be helpful to add a function called has_num or whatever you choose, which takes the FILE* and checks for an int returning 1 if found and 0 if not. So you will modify your if statement to be
if (num != -99 && !has_num(xPtr,num))
{
fprintf(xPtr, "%d\n", num);
}
So with all of those changes, your code will become
#include <stdio.h>
int has_num(FILE* file, int num)
{
int curr;
int fnd = 0;
while (!fnd && (fscanf(file, "%d\n", &curr) != EOF))
{
fnd = (curr == num);
}
return fnd;
}
int main(void)
{
int num;
FILE *xPtr ;
do
{
xPtr = fopen("number.dat", "a+");
printf("Enter a number : ");
scanf("%d", &num);
if (num != -99 && !has_num(xPtr,num))
{
fprintf(xPtr, "%d\n", num);
}
fclose(xPtr);
} while (num != -99);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main(){
FILE *fp; //create a pointer to FILE
char c,n,num;
printf("Enter a Number : ");
scanf("%c",&n);
if(n== -99){
// printf("Enter number greater than -99");
exit(0);
}
else{
fp = fopen("numbers.dat", "r+"); //read file
while ((c = getc(fp)) != EOF) {
num = c;
if(num==n){
printf("Included Number");
exit(0);
}
}
fp = fopen("numbers.dat","w+"); //write new number to file
putc(n, fp);
}
}
You program should successfully append numbers typed by the user to the file, but it has a few problems:
you do not check if fopen() successfully opened the file, you have undefined behavior if fopen() returns NULL.
you do not check if scanf() encountered an input failure. Entering a character that os not a number will cause undefined behavior, most likely an infinite loop appending the previously entered number if any.
you do not close the file. This will not have any adverse effect because all files are automatically closed upon program exit, but it is good style to close them explicitly.
of course you do not check if the number already exists in the file.
For the last problem, you should fopen() the file for both read and write, rewind the file and read all lines, checking if the number is present.
Here is a modified version:
#include <stdio.h>
int main(void) {
int c, num, num1, found;
FILE *xPtr = fopen("number.dat", "w+");
if (xPtr == NULL) {
printf("cannot open file number.dat\n");
return 1;
}
for (;;) {
printf("Enter a number: ");
if (scanf("%d", &num) != 1) {
if (feof(stdin))
break;
printf("invalid input\n");
while ((c = getchar()) != EOF && c != '\n')
continue;
if (c == EOF)
break;
} else {
if (num == -99)
break;
rewind(xPtr);
found = 0;
for (;;) {
/* skip all characters that cannot start a number */
if (fscanf(xPtr, "%*[^-+0-9]") == EOF)
break;
if (fscanf(xPtr, "%d", &num2) == 1) {
if (num == num2) {
found = 1;
break;
}
} else {
getc(xPtr); // consume a byte
}
}
if (found) {
printf("number is already in the file\n");
} else {
/* append the number */
fseek(xPtr, 0L, SEEK_END);
fprintf(xPtr, "%d\n", num);
}
}
}
fclose(xPtr);
return 0;
}
What I am trying to do:
Make a program that opens a file and read the content (mostly characters)
Example on what it should do:
The file contains "ABA", It should print: Letter A Count 2 || Letter B Count 1
but I am getting this error when I start debugging http://imgur.com/a/zvpWg
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <ctype.h>
struct arr
{
char letter;
int count;
};
void main ()
{
arr s[7];
char letter;
FILE *fp;
fp=fopen("D:\\data.txt","r");
if(fp==NULL)
{
printf("Error File Not Found\n");
getch();
exit(1);
}
while(fscanf(fp,"%ch",&letter)!=EOF)
{
for(int i=0;i<7;i++)
{
if(!isalpha(s[i].letter))
{
s[i].letter=letter;
s[i].count=1;
break;
}
else if(s[i].letter == letter)
s[i].count++;
break;
}
}
for(int h=0;h<7;h++)
printf("Letter: %c Count: %d ||",s[h].letter,s[h].count);
getch();
}
Where am i wrong exactly ?
The Problem might be -
function isalpha() is being called with an integer whose value is not a single byte i.e. 0-255.
I wrote the following code but when i enter "abcd" it shows "dcb" and skips the first character.I know that my logic in the while loop crosses the file boundary but fseek(f2) is still not 0 when it crosses the file boundary.It should return some negative value.
#include<stdio.h>
int main()
{
FILE *f1,*f2;
char ch;
clrscr();
f1=fopen("Input","w");
while((ch=getchar())!=EOF)
putc(ch,f1);
fclose(f1);
f2=fopen("Input","r");
fseek(f2,-1L,2);
while(ftell(f2)!=0)
{
ch=getc(f2);
printf("%c",ch);
fseek(f2,-2L,1);
}
fclose(f2);
getch();
return(0);
}
You need a do-while loop, not a while-do loop.
You need to read the character when ftell() returns zero, but NOT read anymore. That's usually the indication you need a bottom-tested loop and not a top tested one.
#include <stdio.h>
int main(){
FILE *fp;
int ch;
fp=fopen("out.txt","w");
while((ch=getchar())!=EOF)
fputc(ch,fp);
fclose(fp);
fp=fopen("out.txt","rb");
fseek(fp,0L,SEEK_END);
while(fseek(fp,-2L,SEEK_CUR)==0){
ch=fgetc(fp);
putchar(ch);
}
fclose(fp);
return(0);
}
I'm creating a program that asks the user to input a word. The word is then compared with a word in a text file. If correct, I want the user to input another word which should correspond with the next word in the text file and this should loop until the end of the file. I'm having trouble with the loop to the end of the file. Could someone please review my code and give me a few pointers? thanks so much
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
//Step 1: open file and declare variables//
FILE *fp;
fp = fopen("secretwords.txt","r");
char guess[20];
char secret[20];
int i, count;
//Step 2: Check that file opened correctly, terminate if not//
if (fp == NULL)
{
printf("Error reading file\n");
exit (0);
fclose(fp);
}
//Step 3: Create loop to run for each word to run to end of file//
fscanf(fp,"%s", secret);
//Need to create a loop here that will read the text file 20 times,
// each time reading the next word//
for (i=0; i < 3; i++)
{
printf("Please guess the word: \n");
scanf("%s", guess);
if (strcmp(secret,guess)==0)
{
printf("Your guess was correct\n");
return 0; //This return will terminate the program.
// I need to restart loop from here
}
else
{
printf("Your guess was incorrect. Please try again\n");
}
}
return 0;
}
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
FILE *fp = fopen("secretwords.txt", "r");
if (fp == NULL)
{
printf("Error reading file\n");
return 1;
}
char guess[20] = {0};
char secret[20] = {0};
while(fscanf(fp, "%s", secret) != EOF) // i would suggest you use 'fscanf_s("%s", guess);' instead if available
{
printf("Please guess the word: \n");
scanf("%s", guess); // i would suggest you use 'scanf_s("%s", guess);' instead if available
if (!strncmp(secret, guess, sizeof(guess)))
{
printf("Your guess was correct. Continue ...\n");
}
else
{
printf("Your guess was incorrect. Good bye.\n");
break;
}
}
fclose(fp);
return 0;
}
i made some suggestions about scanf_s and fscanf_s, if they are available, use them. But still, i am wondering why they are still teaching bad code in schools? I would not suggest to use *scanf* functions at all. Further reading: uncontrolled format string
Move the fscanf call that reads from the file to a function that returns the next word
loop for user input, only calling the function outlined above when you need to advance to the next word in the file (when the user inputs the correct thing)