fprintf places in odd value when processing char value - c

I am writing what should be a simple program, but I'm having an odd issue with fprintf I have not been able to solve.
I am reading a small CSV text file and writing those values to a separate file containing only the numeric values.
My CSV file looks like this.
000,001,002,
003,004,005,
006,007,008,
009,010,011,
255,255,255
There is a comma between each value and a return at the end of each line.
The code I am using is
#include <stdio.h>
#include <string.h>
int main(int argc, char ** argv) {
FILE * inputFile;
FILE * outFile;
char * filename;
int records = 0;
char line[15];
char * sp;
char appendString[] = ".hex";
printf("useage: dec2hex inputFile.txt\n");
// Check if a filename has been specified in the command
if (argc < 2) {
printf("Missing Filename\n");
return (1);
} else {
filename = argv[1];
printf("Read in Filename : %s\n", filename);
}
// Open file in read-only mode
inputFile = fopen(filename, "r");
if (inputFile == NULL) {
printf("Hey! Failed to open the file\n");
return (1);
}
strcat(filename, appendString);
printf("write out filename : %s\n", filename);
outFile = fopen(filename, "w");
while (fgets(line, 15, inputFile) != NULL) {
sp = strtok(line, ",");
char Y_pos = atoi(sp);
sp = strtok(NULL, ",");
char X_pos = atoi(sp);
sp = strtok(NULL, ",");
char OType = atoi(sp);
//print to file
fprintf(outFile, "%c", Y_pos);
fprintf(outFile, "%c", X_pos);
fprintf(outFile, "%c", OType);
records++;
}
fprintf(outFile, '\0');
printf("records = %d\n", records);
fclose(inputFile);
fclose(outFile);
return (0);
}
This will write to a file ..hex
The output I'm expecting should be
000102030405060708090a0bffffff
However what I'm seeing is an odd value inserted $D0.
I'm expecting $0A which does happen afterwards. I have tried some other values in my CSV (from 0 to 50) and this for now seems to be the only value that is random.
The reason I'm using %c in my fprintf is that I only need values from 0-255.
My first question, is why the odd value when processing 010?
How can this be corrected?
I'm using the TCC compiler 0.9.26, but have gotten similar results when using VS.
Thanks

However what I'm seeing is an odd value inserted $D0 $0D.
File was opening in text mode and when writing a code 10 ('\n'), incurred a "\n" to "\r\n" translation on OP's machine.
Instead open the file in binary mode.
// outFile = fopen(filename, "w");
outFile = fopen(filename, "wb");
Note: Other code short-comings exist.

you do not this strtok and atoi magic or binary mode opening magic
int main(void)
{
char line[1000];
while (fgets(line, 100, stdin) != NULL)
{
int X,Y,O;
if(sscanf(line, "%d,%d,%d,", &Y, &X, &O) != 3) { /* error handling*/ }
else
{
printf("%02x ", Y);
printf("%02x ", X);
printf("%02x ", O);
}
}
}
https://godbolt.org/z/vvKGzdcvd

Related

How to get all the content using fprintf in c

I'm trying to print all content of my file but I'm unable to print that to the filebut just first line is being printed, Suggest some way for the same.
First it was just printing 1 line when I hadn't used while loop
When I used while loop with !EOF condition then it didn't even get into while loop and thus was not printing any content.
static void
processNode(xmlTextReaderPtr reader) {
const xmlChar *name, *value;
FILE *fp = fopen("telemetryOutput.txt", "w+");
name = xmlTextReaderConstName(reader);
if (name == NULL)
name = BAD_CAST "--";
value = xmlTextReaderConstValue(reader);
fprintf(fp, "%s\n", "Testing");
// facing issue in this portion:
fprintf(fp, "%d %d %s %d %d",
xmlTextReaderDepth(reader),
xmlTextReaderNodeType(reader),
name,
xmlTextReaderIsEmptyElement(reader),
xmlTextReaderHasValue(reader));
/////
if (value == NULL)
fprintf(fp, "\n");
else {
if (xmlStrlen(value) > 40)
fprintf(fp, " %.40s...\n", value);
else
fprintf(fp, " %s\n", value);
}
}
/**
* streamFile:
* #filename: the file name to parse
*
* Parse and print information about an XML file.
*/
static void
streamFile(const char *filename) {
xmlTextReaderPtr reader;
int ret;
reader = xmlReaderForFile(filename, NULL, 0);
if (reader != NULL) {
ret = xmlTextReaderRead(reader);
while (ret == 1) {
processNode(reader);
ret = xmlTextReaderRead(reader);
}
xmlFreeTextReader(reader);
if (ret != 0) {
fprintf(stderr, "%s : failed to parse\n", filename);
}
} else {
fprintf(stderr, "Unable to open %s\n", filename);
}
}
int main(int argc, char **argv) {
if (argc != 2)
return(1);
/*
* For creating file
*/
FILE *fptr = fopen("telemetryOutput.txt", "rb+");
char there_was_error = 0;
char opened_in_read = 1;
if(fptr == NULL) //if file does not exist, create it
{
opened_in_read = 0;
fptr = fopen("telemetryOutput.txt", "wb");
if (fptr == NULL)
there_was_error = 1;
}
if (there_was_error)
{
printf("Disc full or no permission\n");
return EXIT_FAILURE;
}
/*
* this initialize the library and check potential ABI mismatches
* between the version it was compiled for and the actual shared
* library used.
*/
LIBXML_TEST_VERSION
streamFile(argv[1]);
/*
* Cleanup function for the XML library.
*/
xmlCleanupParser();
/*
* this is to debug memory for regression tests
*/
xmlMemoryDump();
// File Handling
if (opened_in_read)
printf("The file is opened in read mode."
" Let's read some cached data\n");
else
printf("The file is opened in write mode."
" Let's do some processing and cache the results\n");
return EXIT_SUCCESS;
return(0);
}
#else
int main(void) {
fprintf(stderr, "XInclude support not compiled in\n");
exit(1);
}
#endif
I have tried using below method but was unable to get required content
while(!EOF){
fprintf(fp, "%d %d %s %d %d",
xmlTextReaderDepth(reader),
xmlTextReaderNodeType(reader),
name,
xmlTextReaderIsEmptyElement(reader),
xmlTextReaderHasValue(reader));
}
Your logic is wrong. Initially file pointer is at the EOF since the file is empty. Thus it doesn't get into the loop itself.
If you have to print to file only 1 line don't use that condition for while loop.
Also open file in append mode otherwise it might overwrite from start each time you write on it.

Better way to convert string to integer

I wrote this code to read a variable in a .txt file, ignore the first character and convert into a integer.It works but looks dumb, is there a better way to do this? I'm using just one string here but it's supposed to work with four.
void read(char a[])
{
int i;
char a1[3];
for (i = 0; i<3; ++i){
a1[i]= a[i+1];
}
int b1 = atoi(a1);
}
int main()
{
FILE *file;
file = fopen( "file.txt", "r");
if (file == NULL) {
printf( "Arquivo nao encontrado\n");
}
char a[4];
fscanf(file, "%s\n",&a);
read(a);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
const char filename[] = "file.txt";
FILE *fp = fopen(filename, "r");
if (fp == 0)
{
fprintf(stderr, "Failed to open file %s for reading\n", filename);
return(EXIT_FAILURE);
}
int value;
if (fscanf(fp, "%*c%d", &value) != 1)
{
fprintf(stderr, "Failed to read integer value from file %s\n", filename);
fclose(fp);
return EXIT_FAILURE;
}
printf("Read %d\n", value);
fclose(fp);
return 0;
}
The %*c reads a single character but does not assign it. The * to suppress an assignment is a general mechanism in the scanf()
family of functions.
Untested code.

Get integer after a character from file

I'm trying to read the number of a txt file like this:
input=20
output=10
hidden=5
....
I tried with this code:
char line[30];
char values[100][20];
int i = 0;
FILE *fp;
fp = fopen("myFile.txt", "r");
if(fp == NULL)
{
printf("cannot open file\n");
return 0;
}
while(fgets(line, sizeof(line), fp) != NULL)
{
sscanf(line, "%[^=]", values[i])
printf("%s\n", values[i]);
i++;
}
fclose(fp);
But I obtain only the first word and never the number after the =.
I get
input
output
etc
instead of
20
10
5
etc
How can I get the number??
This line
sscanf(line, "%[^=]", values[i]);
means "read everything up to, but not including, the = sign into values[i]".
If you are interested in the numeric part after the equal sign, change the call as follows:
sscanf(line, "%*[^=]=%19s", values[i]);
This format line means "read and ignore (because of the asterisk) everything up to, and including, the equal sign. Then read a string of length of up to 19 characters into values[i]".
Demo.
Don't use sscanf() for that, redeclare values to store the integers like
int values[LARGE_CONSTANT_NUMBER];
and after fgets() just use strchr
char *number;
number = strchr(line, '=');
if (number == NULL)
continue;
number += 1;
values[i] = strtol(number, NULL, 10);
you could also use malloc() and realloc() if you wish, to make the values array dynamic.
Try it if you like
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
char line[100];
int values[100];
int i;
FILE *fp;
size_t maxIntegers;
fp = fopen("myFile.txt", "r");
if (fp == NULL)
{
perror("cannot open file\n");
return 0;
}
i = 0;
maxIntegers = sizeof(values) / sizeof(values[0]);
while ((fgets(line, sizeof(line), fp) != NULL) && (i < maxIntegers))
{
char *number;
number = strchr(line, '=');
if (number == NULL) /* this line does not contain a `=' */
continue;
values[i++] = strtol(number + 1, NULL, 10);
printf("%d\n", values[i - 1]);
}
fclose(fp);
return 0;
}
with this technique you avoid unecessarily storing the number as a string.

Printing multiple strings with printf in C [duplicate]

I am trying to read in a file, find the string "myprop" and after "myprop" will be an "=" sign then a number. I need to print out just that number as a string, getting rid of blank spaces and comments. I am able to locate the "myprop" string and then I believe I should be using fscanf but I am having trouble with that.
const char *get_filename_property()
{
const char *filename = "myfile.properties";
const char *propkey = "myprop";
char buffer[100], *buffPtr, lastChar, value[50];
int line_num=1, i=0;
FILE *fp;
fp=fopen("myfile.properties", "r");
if (fp == NULL)
perror("Error opening file\n\n");
while(fgets(buffer, 100, fp) != NULL)
{
if((strstr(buffer, propkey)) != NULL)
{
printf("Myprop found on line: %d\n", line_num);
printf("\n%s\n", buffer);
}
line_num++;
}
if (fp)
fclose(fp);
}
int main(int argc, char *argv[])
{
get_filename_property();
system("pause");
return(0);
}
You can add sscanf in the moment when you find the mypop string in the file. Add the following line in your while loop:
sscanf(buf,"%*[^=]= %[^\n]",value);
"%*[^=]": This means that scanf capte all characters befor the = and ignore it
" %[^\n]": This means that you are capting all characters after the = till the end of your buffer string (even the space characters). only the space characters in the beggining of the value string will not capted
add it in this way
while(fgets(buffer, 100, fp) != NULL)
{
if((strstr(buffer, propkey)) != NULL)
{
printf("Myprop found on line: %d\n", line_num);
printf("\n%s\n", buffer);
sscanf(buf,"%*[^=]= %[^\n]",value);
printf("\nvalue is %s\n", value);
break;
}
line_num++;
}

reading a string from a file

I have one text file. I have to read one string from the text file. I am using c code. can any body help ?
Use fgets to read string from files in C.
Something like:
#include <stdio.h>
#define BUZZ_SIZE 1024
int main(int argc, char **argv)
{
char buff[BUZZ_SIZE];
FILE *f = fopen("f.txt", "r");
fgets(buff, BUZZ_SIZE, f);
printf("String read: %s\n", buff);
fclose(f);
return 0;
}
Security checks avoided for simplicity.
This should work, it will read a whole line (it's not quite clear what you mean by "string"):
#include <stdio.h>
#include <stdlib.h>
int read_line(FILE *in, char *buffer, size_t max)
{
return fgets(buffer, max, in) == buffer;
}
int main(void)
{
FILE *in;
if((in = fopen("foo.txt", "rt")) != NULL)
{
char line[256];
if(read_line(in, line, sizeof line))
printf("read '%s' OK", line);
else
printf("read error\n");
fclose(in);
}
return EXIT_SUCCESS;
}
The return value is 1 if all went well, 0 on error.
Since this uses a plain fgets(), it will retain the '\n' line feed at the end of the line (if present).
void read_file(char string[60])
{
FILE *fp;
char filename[20];
printf("File to open: \n", &filename );
gets(filename);
fp = fopen(filename, "r"); /* open file for input */
if (fp) /* If no error occurred while opening file */
{ /* input the data from the file. */
fgets(string, 60, fp); /* read the name from the file */
string[strlen(string)] = '\0';
printf("The name read from the file is %s.\n", string );
}
else /* If error occurred, display message. */
{
printf("An error occurred while opening the file.\n");
}
fclose(fp); /* close the input file */
}
This is a Simple way to get the string from file.
#include<stdio.h>
#include<stdlib.h>
#define SIZE 2048
int main(){
char read_el[SIZE];
FILE *fp=fopen("Sample.txt", "r");
if(fp == NULL){
printf("File Opening Error!!");
}
while (fgets(read_el, SIZE, fp) != NULL)
printf(" %s ", read_el);
fclose(fp);
return 0;
}

Resources