File Handling in c not producing the required result - c

I am new to file handling, when I tried to read data from keypad to file and output the contents of that file on the screen I am not getting the desired result with the code below
/* get data from the keyboared till the end of file and write it to the
file named "input" agian read the data from this file on to the screen*/
#include <stdio.h>
int main()
{
FILE *fp;
char c;
printf("enter the data from the keyboared\n");
fp=fopen("input.txt","w");
while((c=getchar()!=EOF))
{
putc(c,fp);
}
fclose(fp);
printf("reading the data from the file named input\n");
fopen("input.txt","r");
while((c=getc(fp))!=EOF)
{
printf("%c",c);
}
fclose(fp);
return 0;
}
I am getting output something like this h ?
Also is there a way so that i can find out where on the harddisk this file is created?

First up, this is wrong because of precedence.
while((c=getchar()!=EOF))
^
Instead of storing the character, you will continuously store the comparison between the character and EOF. So you will continuously store a long line of 1.
Try this:
while((c=getchar())!=EOF)
^
Second getc and getchar return int. So ch should be int, not char. Using a char could mean the loop will never terminate on some systems.

The line:
fopen("input.txt","r");
Is obviously wrong. Seems you want:
fp = fopen("input.txt","r");
Instead.

Related

how to print in terminal from a txt file

So I'm currently learning file processing for my assignment, and I'm wondering why this code
#include<stdio.h>
int main(){
char test[255];
FILE *open;
open = fopen("data.txt", "r");
while(fscanf(open, "%s", test)!=EOF){
printf("%s", test);
}
}
works while the following one
#include<stdio.h>
int main(){
char test[255];
FILE *open;
open = fopen("data.txt", "r");
fscanf(open,"%s", test);
printf("%s", *test);
}
didn't, any answer would be appreciated!
Your second solution does not work because of this line:
printf("%s", *test);
You provide the first character of text[] as parameter, and printf() tries to use it as a pointer for its format "%s". This is Undefined Behavior. Most probably your program crashes at this point.
Remove the dereferencing operator * and it will work in the sense that at most one sequence of non-whitespace characters are output:
printf("%s", test);
On success, the fscanf() function returns the number of values read and on error or end of the file it returns EOF or -1
Now if you do not put this function inside a while loop, it will read one character only. Essentially we want it to run as long as there is data to read inside the text file so we put it inside a while loop, so as long as the file has data to read, it will not return an EOF or a -1 so it will keep on executing and read the data from the file.
For further explanation check fscanf() Function in C

C Programming code will not stop reading from text file

I am trying to read data from a text file and print when a person enters a room and when someone exited the room. The text file is data from a sensor our Professor helped us collect. The file contains angles and ranges detected by the sensor (he spelled “angle” as “angel” in the text file).
The problem I am having is the program will read the file and print what I want it to but it will not stop reading the file. I also need to add a counter that will add one each time a person walked in and subtract one every time a person walked out but I cannot add the counter and get it to print until I fix the code and get it to stop reading the text file. My current code is below. Please help me solve this and Thank You!!
#include <stdio.h>
int main() {
FILE *fp;
FILE *op;
int time;
int range;
float i;
float angel;
char str;
fp = fopen("/home/chris/Desktop/test.txt", "rt");
op = fopen("/home/chris/Desktop/Pro.csv", "w");
i=0;
while((str = getc(fp)) != EOF) {
fscanf(fp,"range: %d, ",&range);
fscanf(fp,"angel: %f,",&angel);
if (angel == -10.75)
{
if(range<4100) {
printf("Someone has entered the room\n");
}
}
if (angel == -10.75)
{
if (range>4100 && range<6000)
printf("Someone has left the room\n");
i++;
}
}
fclose(fp);
fclose(op);
return 0;
}
The return type of getc() is int, but your str variable is char. It might be the case that your system uses a value of EOF that is outside the range of a char.
line 13, getc() returns an int. you need to convert it to char
since the int is not possible you are getting a NULL
fgetc() is a more likely answer.
look at;
https://stackoverflow.com/questions/1835986/how-to-use-eof-to-run-through-a-text-file-in-c
it better explains the return

Trying to write to a file

I am trying to open and then write to a .dat file. The file is just a simple series of numbers, but i would like to add to it. Right now the fputs isn't working for me.
I was wondering if I am using the right function to do the job. Right now it says i can't use the integer enter_this in the function fputs because it is not a constant character.
I want to ask the user to add a integer to the file. My next step after i understand this is to add strings, floats, characters and more. But just getting something that is working is good.
#define _CRT_SECURE_NO_WARNINGS
#include
#include
#include
#include
#include
#include
#include
#include
//functions called
//why is it void?
int main(void)
{
FILE *pFile;
int choice = 0;
char buf[40];
int i = 0;
int num[40];
int enter_this;
printf("WELCOME. \n\n");
pFile = fopen("test.dat", "r");
if (pFile != NULL)
for (i = 0; i < 8; i++)
{
//get num
fgets(buf, sizeof(buf), pFile);
num[i] = atoi(buf);
printf("#%i = %i\n", i, num[i]);
}
printf("Enter number to be added: ");
gets_s(buf);
enter_this = atoi(buf);
fputs(enter_this, pFile);
fclose(pFile);
system("pause");
}//end main
int main(void)
The 'void' in this case implies that the function 'main' accepts no arguments. If you just leave empty parens in C, it implies that the function accepts a variable number of arguments, not 0 as you might expect.
If you want to add a number to the end of the file, you must open it in "append mode":
FILE *pFile = fopen("test.dat", "a");
The second argument "a" is a mode string. It tells fopen to open the file for appending, ie, data will be written at the end of the file. If the file does not exist, it is created. You're currently opening the file in "read only" mode & will not be able to write to it at all. Read about the different mode strings fopen takes here.
Your check to see if the file pointer is NULL is also redundant. You have passed no block to the 'if' to run when the pointer is not NULL. It should be something like:
if (!pFile) {
puts("Something went wrong");
exit(1);
}
Finally, fputs takes a STRING value, ie, a character constant. It will refuse to work with enter_this because it is an integer. One way to write the integer to your file is to use fprintf. For example:
/* Write the integer enter_this & a newline to pFile */
fprintf(pFile, "%d\n", enter_this);

trouble reading a text file

I am trying to read a txt file with following contents:
test.txt
3,4
5,6
7,8
each pair is in one line. I want to put these values in an array. But I want the array size to adjust based on number of pairs in the test txt.
So I calculated the number of lines available in the txt file until EOF and assigned the number of lines to the array to assign the sizeof the array.Then when I try to read the file using fscanf I get some weird numbers which is not even part of this txt file like 2342,123123.
Here is my code:
#include <stdio.h>
int main(int argc , char **argv)
{
FILE *pf;
int k;
int counter=0;
int c;
pf = fopen("test.txt", "r");
if(pf==NULL)
{
printf("its nuull");
}
else
{
do
{
c=fgetc(pf);
if(c=='\n')
counter++;
}while(c!=EOF);
printf("counter value is = %d\n", counter);
int b[counter][2];
for(k=0;k<counter;k++)
{
fscanf(pf,"%d, %d" ,&b[k][0],&b[k][1]);
printf("%d,%d\n" ,b[k][0],b[k][1]);
}
}
fclose(pf);
}
I think you need to call:
rewind(pf);
after displaying your counter value.
This will reset the file pointer to the start of the file.
The issue is probably that the current file pointer is pointing at the end of the file. You need to read from the begining of the file now, so you need to do something like:
rewind(pf);
There are other mechanisms - for instance fseek or fsetpos, but rewind is what I would use here.
You might also check the return from fscanf - this will return the number of input items assigned. If this isn't 2 (in your case) then something went wrong.

trouble using fread in c

Im having some trouble figuring out how to properly format fread statements. The below code is just some randomn stuff Im practicing with. Basically it fills information into the first array (s), writes 's' to a file, and then reads the file into the second array (s2). However I can't seem to get the fread statement formated in a way that doesnt give an error or return garbage. The arrays are in char datatype because, if my understanding is correct, char uses less memory than other datatypes. The eventual application of this practice code is for a data compression project.
#include<stdio.h>
#include<string.h>
FILE *fp;
//file pointer
char s[56];
//first string
char s2[56];
//target string for the fread
int n=0;
//counting variable
int m=0;
int main (void)
{
fp=fopen("test.bin", "w+");
//open a file for reading and writing
strcpy(s, "101010001101010");
//input for the string
for(n=0;n<56;n++)
{
if(s[n]==1)
m=n;
else if(s[n]==0)
m=n;
}
printf("%d\n", m);
//the above for loop finds how many elements in 's' are filled with 1's and 0's
for(n=0;n<m;n++)
{
printf("%c", s[n]);
}
//for loop to print 's'
fwrite(s, m, 1, fp);
//writes 's' to the first file
s2=fread(&s2, m, 1, fp);
//an attempt to use fread...
printf("\n\ns2\n\n");
for(n=0;n<m;n++)
{
printf("%c", s2[n]);
}
printf("\n");
//for loop to print 's2'
fclose(fp);
printf("\n\n");
printf("press any number to close program\n");
scanf("%d", &m);
}
A FILE structure has an implicit seek position within the file. You read and write from that seek position. If you want to read what you have written, you need to change the seek position back to the beginning of the file with a call to fseek(). In fact, for a file open for reading and writing, you must call fseek() when switching between reading and writing.
The return value of the fread function is of type size_t. It is the number of elements successfully read. (reference: http://www.cplusplus.com/reference/cstdio/fread/)
Don't assign it to s2. Simply use fread(&s2, m, 1, fp);

Resources