How can i read file and assign the file content into variable using C ?
for example: program.txt file is contain values like this
r1=2r2=4r3=5r4=6
i want to read the program.txt file and assign r1,r2,r3,r4 values to variable.
i tried with this example program, but it returns too many argument for fgetchar().
#include <stdio.h>
int main()
{
int n;
char c;
FILE *fptr;
if ((fptr=fopen("E:\\program.txt","r"))==NULL){
printf("Error! opening file");
}
fscanf(fptr,"%d",&n);
fgetchar(fptr);
printf("Value of n=%d",n);
printf("Char is = %c", c);
fclose(fptr);
return 0;
}
the problem is that you ask fscanf to read an integer: fscanf(fptr, "%d", &n);
but your first character in the file is a letter. so fscanf can not find an int so it fails and stop there.
The solution is to write your assignation as one per line like that:
r1=1
r2=2
r3=3
then you ask fscanf to match the line and in place of the number you want to read to put the %d so it looks like that: fscanf(ftpr, "r%d=%d\n", &n, &var);
By the way: fgetchar does not exists, so there is no way your program actually compile, but you can use: fgetc that takes the FILE as argument and returns the next character in the file: char c = fgetc(fptr);
There is no magic way to do this. YOu have to do the heavy lifting yourself
if you can reorg the file so its like Lavigne958 suggests
Then you need to do
int val[10];
while(!feof(fptr))
{
fscanf(ftpr, "r%d=%d\n", &n, &var);
val[n] = var;
}
if they must be called r1, r2, r3, ... then do
int *val[10];
val[1] = &r1; // yes I know I missed out [0]
val[2] = &r2;
...
while(!feof(fptr))
{
fscanf(ftpr, "r%d=%d\n", &n, &var);
*(val[n]) = var;
}
Related
Its my first question, so I hope you guys can help. In class, I was tasked with writing a C code that reads a group of strings from 1 file, and print them in another file, along with the ASCII codes of each character in the string, and the sum of the ASCII code values. The code below compiled, but did not execute. Is the code right, but I did something wrong, or is the code simply wrong. Thanks a bunch.
Note: the first file reads from a text file named list, and the code prints into a text document named list2.
#include <stdio.h>
int main(void)
{
FILE *file1, *file2;
file1 = fopen("list.txt", "r");
if (file1==NULL)
{
puts(" File not exisiting\n");
}
file2 = fopen("list2.txt", "w");
if (file2==NULL)
{
puts(" File could not open \n");
}
char a[5];
fscanf(file1, "%s", a);
int b,c;
while (a[5]!=EOF)
{
for (int i=0;i<5;i++)
{
fprintf(file2, "%c", a[i]);
b=a[i];
fprintf(file2, "%d", b);
c+=b;
}
}
fprintf(file2, "%d", c);
return 0;
}
Point 1. With a definition like
char a[5];
using
while (a[5]!=EOF)
invokes undefined behaviour.
You're facing off-by-one error. Remember, array index in c starts from 0. The valid access it at most upto a[4].
Point 2. fscanf(file1, "%s", a); is unsafe. It can cause buffer overflow. Atleast, you need to write
if ( fscanf(file1, "%4s", a) != 1)
{
//scanning not successful, take necessary measures
}
//otherwise, continue nomal execution.
Point 3. The logic for while loop is not correct. You don't have a break condition there.
Point 4. c+=b;, here c is used uninitalized. read-before-write scenario. Again, undefined behaviour. Remember, auto local variables doesnot get initialized to 0 or some value automatically. You've to initialize explicitly.
Point 5. Do not continue normal execution if if (file1==NULL) condition satisfies. Only printing a message is not sufficient. You should discontinue the program and avoid using file1, file1 etc.
Credits for point 5: user4402433
Include return in the file check as
if (file1==NULL)
{
puts(" File not exisiting\n");
return 0;
}
as there is no use of proceeding with the code if any one of the file is opened.
Also initialize the value of c=0; before while so that any garbage value can be avoided.
The array a[] has to be indexed to update the file content. So place the
fscanf(file1, "%s", a[i]);
inside the for() loop . This is to avoid buffer overflow which occurs in rare cases.
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);
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.
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.
I have the following in a text file called: values.txt
1 4
2.5 3.76
122 10
277.543
165.4432
I am trying to read the content of this text file, and add each two pairs together and output the result ...
the output would be something like this :
1 Pair:(1, 4) = 5
2 Pair:(2.5, 3.76)= 6.26
and so on ..
I am opening the file like this
int c;
FILE myfile;
myfile= fopen("values.txt", "r");
if ( myfile == NULL ) {
printf("Cannot open TEXT file\n");
return 1;
}
double aa,bb;
while ( (c = getc(myfile) ) != EOF ) {
// HERE SHOULD I DO THE OUTPUT BUT HOW?
}
Any help is really appreciated ..
Language = C
The following code does what you expect. myfile should be declared as FILE*. fopen returns a pointer to FILE structure. If the file is very large, I would recommend reading in buffers of big size (eg: 65535 etc) and parse it char by char and convert it to float values. It reduces system call overhead which takes more time than processing text to float values.
#include <stdio.h>
#include <string.h>
main(int argc, char *argv[])
{
FILE* myfile;
myfile = fopen("values.txt", "r");
if ( myfile == NULL ) {
printf("Cannot open TEXT file\n");
return 1;
}
double aa,bb;
while (2 == fscanf(myfile, "%lf %lf", &aa, &bb)) {
printf("%lf\n", aa+bb);
}
return 0;
}
For this simple task, use double a, b;
if (fscanf(myfile, "%lf %lf", &a, &b) == 2)
printf("%f + %f = %f\n", a, b, a+b);.
looks like a homework problem but fscanf can read the string into a variable like:
int n;
fscanf (myfile,"%d",&n);
You haven't shown what you need as output for the single-value lines, but this looks like a case for fgets() and sscanf(), unless you really want the two lines with a single value to be processed as a unit.
char buffer[256];
int rownum = 0;
while (fgets(buffer, sizeof(buffer), myfile) != 0)
{
double aa, bb;
int n = sscanf(buffer, "%lf %lf", &aa, &bb);
if (n == 2)
printf("%d Pair:(%g, %g) = %g\n", ++rownum, aa, bb, aa+bb);
else if (n == 1)
printf("%d Solo:(%g) = %g\n", ++rownum, aa, aa);
else
{
printf("Failed to find any numbers in <<%s>>\n", buffer);
}
}
If you used fscanf(myfile, "%g %g", &aa, &bb), then it would read over newlines (they count as white space) looking for numbers, so it would read one number from one line, and the second from another line. This is not usually what people are after (but when it is what you need, it is extremely useful). Error recovery with fscanf() tends to be more fraught than with fgets() and sscanf().
its in c++ sorry :( i dont know c
this is a very simple logic code for simple minde :D im a begineer too, i havent tested this prog so sorry if something goes wrong but exactly
on a same principle was working my parser and it worked fine. so this is a true method. not very efficent but...
do not use this program straight away, understand it's logic this will help you alot. copying that wont give you anything
...parser tutors are so rare....
int x=0;
char ch = 'r'; //i'v used this equasion to avoid error on first ckeck of ch.
it must be filled by something when program starts.
char bigch[10];
int checknumber = 0;
float firstnumber = 0;
float secondnumber = 0;
float result=0;
void clearar(char frombigar[10], int xar) //this function gets bigch as a reference which means that eny
changes made here, will directly affect bigch itself.
ths function gets the actual length of array and puts spaces
in bigch's every element to zero out numbers. we need to clear
bigch of any previous numbers. down below you'l see why i needed this.
'xar' is the x from main function. its here to tell our cleaner the
true length of filled bigar elements.
{
for (int i=0; i
}
}
int main()
{
<------------------- //here you add file opening and reading commands
while(!myfile.eof()) //while end of txt file have not been reached
{
ch=myfile.get(); //gets each letter into ch, and make cursor one step
forward in txt file for further reading.
get() does cursor forwarding automatically
if (ch!= " ") //i used space as an indicator where one number ends
//so while space havent been reahced, read letters.
{ bigch[x] = ch; //get read letter into bigch array.
x++; //icrement bigch array step
}
else
if(ch == " ") //if space is reached that means one number has ended and
{ im trying to set a flag at that moment. it will be used further.
checknumber++; the flag is simple number. first space will set checknumber to 1
second space will set it to 2. thats all.
}
if (checknumber == 1) //if our checknumber is 1, wich means that reading
of first number is done, lets make one whole float
from that bigch array.
{ firstnumber = atof(bigch); //here we get bigch, atof (array to float) command converts
bigch array into one whole float number.
clearar(bigch,x); //here we send bigch and its element step into function where
bigch gets cleaned because we dont want some ghost numbers in it.
abviously clearar function cleans bigch int main function aswell,
not only in it's teritory. its a global cleaning :)
}
else if (checknumber ==2) //here we do the same but if flag is 2 this means that two spaces
had been passed and its time to convert bigch into secondnumber.
{ secondnumber = atof(bigch); //same method of converting array into float (it hates other
not number letters, i mean if its a number its fine. if in your text
was 'a' or 's' in that case atof will panic hehe.. )
clearar(bigch,x); //same thing, we send bigch to cleaner function to kill any numbers
it, we get one space letter ( " " ) into each element of bigch.
}
checknumber = 0; if both two numbers had been read out and converted. we need to reset
space flagger. and start counting form 0; for next pair numbers.
result = firstnumber+secondnumber; well here everything is clear.
}
}