I have a text file like this
987jgkfl
12358ldjkdju
7579jngj
8uuujkl
09698fjfj
I have a structure like this
struct emprec
{
int empid;
int todo;
char name[20];
};
I write the values of the struct into file like this
fd = fopen("/home/tarun/Desktop/test34.txt","a+");
fprintf(fd,"%d",temp2.empid);
fprintf(fd,"%s",temp2.name);
count++;
fclose(fd);
But when i read from the file i am getting the garbage value
while(i<=count)
{
fread(&temp5,sizeof(temp5),1,fd);
//fscanf(fd,"%d,%s",&temp5.empid,temp5.name);
//int k = strlen(temp5.name);
//printf("Value of k is %d\n",k);
//temp5.name[7]= '\0';
//fread(&temp5.empid,sizeof(temp5.empid),1,fd);
//fread(temp5.name,20,1,fd);
printf("\n%d %s",temp5.empid,temp5.name);
i++;
}
fclose(fd);
Please tell me where am i going wrong
Like say nemetroid :
You're writing a textual representation (with
fptrinf) of your struct but attempting to read a binary representation
(with fread).
For example, suppose you want write an int in a file. By doing like this :
fd = fopen("file","a+");
fprintf(fd,"%d",42);
You will write the character '4' and the character '2'. In ASCII, '4' is 0x34 and '2' is 0x32.
If you want to read that file and try to put it in an 4 bytes integer by doing like this :
int a = 0;
fread(&a,sizeof(a),1,fd);
The variable 'a' will contain the data on the file :
a = 0x00003234
And not 42 (0x0000002a) as you expect.
There were some calls that was missing from your code:
fflush()
Used to flush the file's buffer, you have to call this if you performed writes to the file and now you want to read
fseek
Used to set the file position indicator. In your case, the file position indicator was at the end of the file. Use fseek() to set the file position to where you started writing and than start reading.
fscanf function corresponds to fprintf. fread corresponds to fwrite. It means if you want to dump the structure using fprintf, then read it using fscanf. if you want to read the structure using fread then dump it using fwrite. Referring manpages of these functions should help.
Related
I've been trying to write the contents of an integer array to a file in C. I've been using the code below to do so.
int etData [600];
int i;
int size = sizeof(char);
for (i=0; i<600; i++)
{
etData[i] = analog_et(5);
}
FILE *f = fopen("/home/root/Documents/KISS/Default User/Launch Code/data/data", "w");
fwrite(etData, size, sizeof(etData), f);
fclose(f);
analog_et is a function that returns an integer value from a sensor. Whenever I run this code, a mess of ASCII characters is written to the file. I believe this is to blame on the fact that I am passing fwrite an element size sizeof(char) - however, whenever I attempt to pass a value larger than one byte, nothing is written to the file, and fwrite fails to return a non-zero value.
I've looked for a function in stdio that would be better suited to this purpose but can't find one. Any suggestions on how to fix this issue? Thanks!
If you want a textual representation of your data (in that case the file can be opened with a text editor), you cannot user fwrite but you need to use fprintf. Latter does basically is the same thing as printf, but instead of being displayed, the data is written into a text file.
You probably want this:
...
FILE *f = fopen("/home/root/Documents/KISS/Default User/Launch Code/data/data", "w");
for (i=0; i<600; i++)
{
fprintf("%d\n", etData[i]);
}
...
Hi guys how to read entire digits from file? I mean my input file is 100-4/2 and i wrote this code while(fscanf(in,"%s",s)!=EOF) but it read like this 1 0 0. I want read like 100. How to solve this?
It's probably because you are using one-byte character(ANSI) set while the file is written with two-byte characters(Unicode). If you have created the file with the same program that is reading it it's going to read it right, but if not, you can open the file you are reading in notepad, then click save as, and there you can choose ANSI or Unicode.
You can read the whole line at once using getline() or similar method (also you can read as you are doing if there is only one line, then when EOF is true, whole line is read). Then you can parse the line to extract numbers and operators.
Use "%d" for integers
int value;
if (scanf("%d", &value) != 1) /* error */;
printf("Value read is %d.\n", value);
The below is simple program is self explanatory, which reads a file character by character, for each iteration stores this character into a temporary variable temp. and when the value in temp is a numerical character it simply copies this value in array named s.
int main()
{
char s[10]="\0";//initialzing array to NULL's and assuming array size to be 10
int i=0,temp=0;
FILE *fp=fopen("t.txt","r"); //when file has 100-4/2
if(fp==NULL)
{
printf("\nError opening file.");
return 1;
}
while( (temp=fgetc(fp))!=EOF && i<10 ) //i<10 to not exceed array size..
{
if(temp>='0' && temp<='9')//if value in temp is a number (simple logic...)
{
s[i]=temp;
i++;
}
}
printf("%s",s);//outputs 10042
return 0;
}
I am trying to solve a problem which requires me to read a file and generate another file which has the same contents as the original but every fourth byte removed.I tried it doing this way ...
int main()
{
FILE *p;
FILE *q;
int i=0,k=0;
char c;
p = fopen("C:\\Users\\Teja\\Desktop\\Beethoven.raw","rw");
q = fopen("C:\\Users\\Teja\\Desktop\\Beethoven_new.raw","w+");
printf("%x is the EOF character \n",EOF);
while((c=fgetc(p))!=EOF)
{
if(i==3){
i=0;
printf("Removing %x %d \n",c,k++);
}
else{
printf("Putting %x %d \n",c,k++);
fputc(c,q);
i++;
}
}
fclose(p);
fclose(q);
return 0;
}
The file that i was trying to read is a .raw file and it is around 10-15 MB. I notice that the above code stops reading the file after typically 88 bytes. Is there any way to read large files or am i doing anything wrong ?
In addition to what has already been pointed out, a note on opening files: It sounds like your file in a binary file, which means you must add a b to the mode string. Additionally, rw is not a mode, since you only read from p you want rb, and since you only write to q you want wb or wb+.
By the way, the reason why you need fgetc to return an int is because fgetc must return 257 unique values: all the possible values of char, that is 0x00 thru 0xFF as well as something unique to signify EOF, usually -1
Change
char c;
to
int c;
as the return type of fetgetc() is an int and not char.
I have an embedded board (beagleboard-xm) that runs ubuntu 12.04, I would like to read one GPIO input if it is logic 1 or 0. How can I implement cat /sys/class/gpio/gpio139/value in C? (value file stores 0 or 1)
I open the file by:
FILE *fp;
fp = fopen("/sys/class/gpio/gpio139/value", "rb");
what do I need to do next?
If you want to read one character, try this:
int value = fgetc(fp);
/* error checking */
value = value - '0';
You can read one byte, or until eof:
char buffer[32]; // Very long number!
if (NULL == (fp = fopen(FILENAME, "rb")))
{
// TODO: return a suitable error/perror
return -1;
}
bytesread = fread(buffer, sizeof(char), sizeof(buffer)-1, fp);
fclose(fp);
if (!bytesread)
{
// Nothing at all was read
// TODO: return error
return -2;
}
// This is in case you want the byte interpreted from ASCII
// otherwise you'd just return buffer[0], or (*(DATATYPE *)buffer)[0].
buffer[bytesread] = 0x0;
return atol(buffer);
This code is actually not that general, in that many hardware devices will implement a blocking data channel - that is, if you try to read more data than it's there, the fread will block until data becomes available. In such a case, just dimension the buffer to the maximum number of bytes you need, plus one.
The plus one, and the corresponding -1 in the fread, are only there for the case in which the data you read is rendered as ASCII, i.e., "128" is three ASCII bytes "1", "2", "8" and maybe even a carriage return, instead of a binary 0x80. In this case, the buffer is zero-terminated to make it a C string on which atol may operate to retrieve a decimal number.
If what is needed is a binary value, then no such conversion is needed, and one can read the full buffer without adjustments, avoid setting the last plus one byte to zero, and just return a cast value from the buffer; or buffer[0] if only one byte is needed.
After attempting to open the file, you check that the fopen() succeeded.
Then you can use any of the stdio functions to read the data:
getc()
fgetc()
fgets()
fread()
and probably others too. You might be looking at the scanf() family, but most probably won't be using them, for example. Which is most appropriate depends on the data that is read; is it text or is it binary. If it is a single character, then getc(); if it is text and line-oriented, maybe fgets(); if binary, probably fread().
If you have access to your Linux headers, than I would recommend you to access GPIO using Linux API.
Include this in your file:
#include <linux/gpio.h>
Now you have access to functions like:
int gpio_is_valid(int number);
int gpio_get_value(unsigned gpio);
void gpio_set_value(unsigned gpio, int value);
In your case you can just write this:
int io_ret = -1;
if (gpio_is_valid(139))
io_ret = gpio_get_value(139);
i think it will be better if you used:
system("echo /sys/class/gpio/gpio139/value >> temp.txt ");
after that it is easy you can just extract the value from temp.txt which will be either 0 or 1
I am completely new to C and need help with this badly.
Im reading a file with fopen(), then obtaining the contents of it using fgetc(). What I want to know is how I can access the line fgetc() returns so if I can put the 4th - 8th characters into a char array. Below is an example I found online but am having a hard time parsing the data returns, I still don't have a firm understanding of C and don't get how an int can be used to store a line of characters.
FILE *fr;
fr = fopen("elapsed.txt", "r");
int n = fgetc(fr);
while(n!= EOF){
printf("%c", n);
n = fgetc(fr);
} printf("\n");
Here
1 first open the file
2 get size of file
3 allocated size to character pointer
4 and read data from file
FILE *fr;
char *message;
fr = fopen("elapsed.txt", "r");
/*create variable of stat*/
struct stat stp = { 0 };
/*These functions return information about a file. No permissions are required on the file itself*/
stat("elapsed.txt", &stp);
/*determine the size of data which is in file*/
int filesize = stp.st_size;
/*allocates the address to the message pointer and allocates memory*/
message = (char *) malloc(sizeof(char) * filesize);
if (fread(message, 1, filesize - 1, fr) == -1) {
printf("\nerror in reading\n");
/**close the read file*/
fclose(fr);
/*free input string*/
free(message);
}
printf("\n\tEntered Message for Encode is = %s", message);
PS Dont Forget to Add #include <sys/stat.h>.
You're not retrieving a line with fgetc. You are retrieving one character at a time from the file. That sample keeps retrieving characters until the EOF character is encountred (end of file). Look at this description of fgetc.
http://www.cplusplus.com/reference/clibrary/cstdio/fgetc/
On each iteration of the while loop, fgetc will retrieve a single character and place it into the variable "n". Something that can help you with "characters" in C is to just think of it as one byte, instead of an actual character. What you're not understanding here is that an int is 4 bytes and the character is 1 byte, but both can store the same bit pattern for the same ASCII character. The only different is the size of the variable internally.
The sample you have above shows a printf with "%c", which means to take the value in "n" and treat it like an ASCII character.
http://www.cplusplus.com/reference/clibrary/cstdio/printf/
You can use a counter in the while loop to keep track of your position to find the 4th and 8th value from the file. You should also think about what happens if the input file is smaller than your maximum size.
Hope that helps.
Ok look at it as box sizes I could have a 30cm x 30cm box that can hold 1 foam letter that I have. Now the function I am calling a function that 'could' return a 60cm x 60cm letter but it 99% likely to return a 30cm x 30cm letter because I know what its reading - I know if I give it a 60cm x 60cm box the result will always fit without surprises.
But if I am sure that the result will always be a 30cm x 30cm box then I know I can convert the result of a function that returns aa 60cm x 60cm box without losing anything