issue in file handling in c [closed] - c

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Hi i am trying to read two characters from a file and want to send it to uint8_t* as hexadecimal .
Code:
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
int file_handling();
int main()
{
uint8_t *output ;
output=file_handling() ;
printf("\noutput_main --> %02x",output);
}
int file_handling()
{
uint8_t *output_hand ;
char c;
FILE *f_gets = fopen("filename", "r");
if(f_gets==NULL)
{
printf("Please point to a valid key file!\n");
fclose(f_gets);
return 0;
}
char str[3];
if( fgets (str, 3, f_gets)!=NULL )
{
/* writing content to stdout */
puts(str);
output_hand = (uint8_t *)(str);
puts(output_hand);
printf("\noutput %s --- %02x --> size --> %lu",str,*output_hand,sizeof(*output_hand));
}
fclose(f_gets);
return *output_hand;
}
following is output
we we
output we --- 77 --> size --> 1 output_main --> 65
what i can understand is 77 is ascii for w and 65 is ascii for e
but i want to put "we" which i suppose is a hex in uint8_t *output
where is the problem
in main ,if i use pointer "*output=file_handling()" instead of just output i get segmentation fault.
How to read value from a file and put it into uint8_t , where file is having hex characters,how fget identifies it as hex or char.
Thanks
file is a text file
ab
fe
ea
ce
1d
Basically
uint8_t *output;
*output = 0xFA ;
it works
but i want to read from above file and put it into output variable

You have plenty of problems, here's three of them:
You define str to be an array of two characters, which means it can only contain a single-character string. You then call fgets telling it that str it three characters, which means it can and will write out of bounds of your array.
You have declared file_handling to return an int value. You return the first character in the array string, and assign that to the pointer variable output in the main function. You then treat this pointer as a single int value.
In the main function you pass the pointer output but print it as an int value. There's a mismatch between the format specifier and the argument.
The first and third issues lead to undefined behavior.

Related

Difference between printf("%d", 5) and printf("5") [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
//(1)
#include <stdio.h>
int main() {
printf("%d", 5);
}
//(2)
#include <stdio.h>
int main() {
printf("5");
}
What are the difference between (1) code block, and (2) code block?
The difference is that printf("%d", 5) is used to print (to stdout) the value of a variable of type int.
Whereas printf("5") is used to print (to stdout) a string. To get more clear, let's modify the code slightly.
//(1)
#include <stdio.h>
int var = 5;
int main() {
printf("%d", var);
}
//Output : 5
//(2)
#include <stdio.h>
int var = 5;
int main() {
printf("var");
}
Output : var
As you can see, printf() in (1) interprets var as a variable of type int and then prints its value.
Whereas printf() in (2) interprets var as a string and prints it as it is.
Are you talking about printf or main? I think that you are talking about printf.
Return value
Upon successful return, these functions return the number of characters printed (excluding the null byte used to end output to strings).
The functions snprintf() and vsnprintf() do not write more than size bytes (including the terminating null byte ('\0')). If the output was truncated due to this limit then the return value is the number of characters (excluding the terminating null byte) which would have been written to the final string if enough space had been available. Thus, a return value of size or more means that the output was truncated. (See also below under NOTES.)
If an output error is encountered, a negative value is returned.
Both of those calls should return the number one.
The answer to your question is that they both return an integer. However, you can treat an integer like a char. The ascii table shows you the mapping of integers to chars.
Both the code block will give output as 5 .
Please check the image file.
enter image description here
If you have doubts, just try to use typeof keyword of that variable and check according to that

C- leading zero without printf [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Ethernet starter kit(PIC32MX9795F512L)
language: C
MPLAB IDE 8.92
Compiler: XC32 v1.3
Hello i want to add leading zeros to my variables. At the end i want to use the in an array.
For example: c=10*a+b. When c=5 it should be 05. I cant use any printf function or am I wrong?
You can use printf() to simply print a formatted number to standard output:
int c = 5;
fprintf(stdout, "c [%02d]\n", c);
If you can't use printf(), another option is to store the padded value in a char * or string. You can instead use sprintf() to write the formatted string to a char * buffer.
For example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (int argc, char *argv[]) {
{
char* c_str = NULL;
int c_int = 5;
int c_str_length = 3; /* two bytes for "0", "5", and one byte for the nul terminator */
c_str = malloc(c_str_length);
if (!c_str) {
fprintf(stderr, "Error: Could not allocate space for string!\n");
return EXIT_FAILURE;
}
int n = sprintf(c_str, "%02d", c_int);
if (n != c_str_length) {
fprintf(stderr, "Error: Something went wrong in writing the formatted string!\n");
free(c_str);
return EXIT_FAILURE;
}
fprintf(stdout, "c_str: [%s]\n", c_str);
free(c_str);
return EXIT_SUCCESS;
}
If you go this route, you can see how you could do some error checking along the way. You'll need to think about string length (hint: log10()), or use a static char [] array in place of a char * of sufficiently long length.
It is quite easy to add a leading zero, provided you take care of negative values too. You said you want to write to an array, so I used sprintf but if you want to output directly, you can use printf in a similar way.
char cstr[24];
int c = 10 * a + b;
if (c > 0) {
sprintf(cstr, "0%d", c);
} else if (c < 0) {
sprintf(cstr, "-0%d", -c);
} else {
//sprintf(cstr, "00");
sprintf(cstr, "0"); // depending on your needs
}

Convert character to integer, and integer back to same character [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I want two create two functions that can do this. So one function takes a character, for example the character a and returns the integer 97. The other function takes this integer 97 and returns the character a. I know this can be done by using the ASCII codes of these characters, but then it wouldn't work for characters like é, à, ö. Can this be done using unicode or another way?
For example:
int character_to_integer(char c) {
convert character to integer and return
}
Input: character_to_index('é');
Output: 102 (for example)
char integer_to_character(int i) {
convert integer to character and return
}
Input: integer_to_character(102);
Output: é
I want to do this with it: have an array, so for example int my_array[5] with all elements set to NULL at the start. Then for example, index 0, 3 and 4 (which correspond to a, d and e for example) are set to something other than NULL then I want to loop over it and build a string based off the which indexes aren't NULL, like so:
void build_string_from_array(int my_array) {
char buffer[16];
char c;
for (i = 0; i < 5; i++) {
if (my_array[i] != NULL) {
c = integer_to_character(i);
buffer[i] = c;
}
}
buffer[5] = '\0';
printf("%s\n", buffer);
}
Output: ade
Note, this is just an example, and I know there is probably something wrong with it, but it's just to get my point across. I know this can be done with ASCII codes, where all the characters are only 1 char, but how can this be done so that characters like é, that are seen as 2 chars would also work?
If it's not clear what I mean just ask me and I'll elaborate some more.
For single Byte chars, this is no Problem, since char is a integer:
int i = 'B';
and
char c = 0x33;
will work fine.
But, if you use UTF8 with chars with more than one Byte, you must convert the UTF8-String to a UCS4 String. Sadly there is no Standard API for that.
See also this Post: Converting a UTF-8 text to wchar_t
A other way is use wchar_t everywhere. This will not work well on Windows with chars outside the BMP, since the wchar_t implementation in Windows is brocken (wchar_t is still a Multibyte Character Set on Windows). On Linux it will work, if you not use compound chars.

Text file with different data types into structure array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have to parse a text file with 3 different data types. I want it to be saved in a structure array with three members. My text file look like this:
A B 45.78965
A C 35.46731
B C 46.78695
The program that I'm reading it with is the following and it does not work.
What am I doing wrong?
#include <stdio.h>
struct gra {
char from;
char to;
double w;
};
int main ()
{
FILE *fp = fopen("graph.txt", "r");
int i = 0;
while (!feof(fp)) {
fscanf(fp, "%[^\t]", &graph[i].from, &graph[i].to, &graph[i].w);
i++;
}
fclose(fp);
}
One of your problems is that you're reading using %[^\t], which reads strings, and store the result to variables that are not character arrays (two characters and a double).
Although it's not clear from your question, it seems that the lines of your input contain two characters and one real number separated by one tab character. If that is so, you should use the following fscanf to read them:
fscanf(fp, "%c\t%c\t%lf\n", &graph[i].from, &graph[i].to, &graph[i].w);
If you are not sure what exactly separates your fields and you want to allow any amount of white space in between and also extra white space in the beginning and end of the line, then use:
fscanf(fp, " %c %c%lf\n", &graph[i].from, &graph[i].to, &graph[i].w);
that is, use an extra space in the format before each "%c" to explicitly skip white space.
Your code has also a couple of other problems:
You are using feof to check for end of file. This will usually not work well if you're not reading the file character by character. Instead, you should check if your fscanf returned 3, that is, if it successfully read the three things that you wanted it to read.
You are missing a definition of array graph.
I'm adding the complete code that I'd write for doing the parsing:
#include"stdio.h"
#define MAX 100
struct {
char from, to;
double w;
} graph[MAX];
int main ()
{
FILE *fp = fopen("graph.txt", "rt");
for (int i=0; i<MAX; i++)
if (fscanf(fp, " %c %c%lf\n", &graph[i].from, &graph[i].to, &graph[i].w) < 3)
break;
fclose(fp);
return 0;
}

Text file with different data types into structure arrays [duplicate]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have to parse a text file with 3 different data types. I want it to be saved in a structure array with three members. My text file look like this:
A B 45.78965
A C 35.46731
B C 46.78695
The program that I'm reading it with is the following and it does not work.
What am I doing wrong?
#include <stdio.h>
struct gra {
char from;
char to;
double w;
};
int main ()
{
FILE *fp = fopen("graph.txt", "r");
int i = 0;
while (!feof(fp)) {
fscanf(fp, "%[^\t]", &graph[i].from, &graph[i].to, &graph[i].w);
i++;
}
fclose(fp);
}
One of your problems is that you're reading using %[^\t], which reads strings, and store the result to variables that are not character arrays (two characters and a double).
Although it's not clear from your question, it seems that the lines of your input contain two characters and one real number separated by one tab character. If that is so, you should use the following fscanf to read them:
fscanf(fp, "%c\t%c\t%lf\n", &graph[i].from, &graph[i].to, &graph[i].w);
If you are not sure what exactly separates your fields and you want to allow any amount of white space in between and also extra white space in the beginning and end of the line, then use:
fscanf(fp, " %c %c%lf\n", &graph[i].from, &graph[i].to, &graph[i].w);
that is, use an extra space in the format before each "%c" to explicitly skip white space.
Your code has also a couple of other problems:
You are using feof to check for end of file. This will usually not work well if you're not reading the file character by character. Instead, you should check if your fscanf returned 3, that is, if it successfully read the three things that you wanted it to read.
You are missing a definition of array graph.
I'm adding the complete code that I'd write for doing the parsing:
#include"stdio.h"
#define MAX 100
struct {
char from, to;
double w;
} graph[MAX];
int main ()
{
FILE *fp = fopen("graph.txt", "rt");
for (int i=0; i<MAX; i++)
if (fscanf(fp, " %c %c%lf\n", &graph[i].from, &graph[i].to, &graph[i].w) < 3)
break;
fclose(fp);
return 0;
}

Resources