inverted results when using many fgetc inside the same printf - printf

I have a file archivo3.txt with "ABCDEFGHI", I read the 3 first characters though fgetc SEPARATELY (differents printf) and works properly (41, 42, 43 are displyaed), the problem comes when I try to do the same but using only one printf.
In that case the values are displayed from rigth to left (43,42,41). Does anybody know what happens?
My code is:
#include<stdio.h>
#include<stdlib.h>
int main(){
FILE*app_f=fopen("archivo3.txt", "rb");
if(app_f==NULL){
printf("error al abrir el archivo");
exit(1);
}else{
fseek(app_f,0, SEEK_SET);
printf("caracteres %02X\n", fgetc(app_f));
printf("caracteres %02X\n", fgetc(app_f));
printf("caracteres %02X\n", fgetc(app_f));
printf("\n--------------\n");
fseek(app_f,0, SEEK_SET);
printf("caracter %02X, %02X, %02X\n", fgetc(app_f), fgetc(app_f), fgetc(app_f));
}
return 0;
}

The order that the parameters are evaluated is not defined in any standard and can thus vary from compiler to compiler. It seems your compiler is evaluating the expressions from last to first rather than the other way round. Another compiler may do so in a different order.
It is thus safest not to assume the order in which the printf arguments will be evaluated, and to write your code accordingly. See my snippet below.
For more info see this more thorough question
#include<stdio.h>
#include<stdlib.h>
int main(){
chars = char[3];
FILE*app_f=fopen("archivo3.txt", "rb");
if(app_f==NULL){
printf("error al abrir el archivo");
exit(1);
}else{
fseek(app_f,0, SEEK_SET);
chars[0] = fgetc(app_f);
chars[1] = fgetc(app_f);
chars[2] = fgetc(app_f);
printf("caracteres %02X\n", chars[0]);
printf("caracteres %02X\n", chars[1]);
printf("caracteres %02X\n", chars[2]);
printf("\n--------------\n");
fseek(app_f,0, SEEK_SET);
printf("caracter %02X, %02X, %02X\n", chars[0], chars[1], chars[2]);
}
return 0;
}

Related

how to get (segment offset) each different plane (IODeviceTree, IOService ....) to make a dump?

I want to read analyze a plane (IODeviceTree IOUSB IOService IOACPIPlane)
without using ioreg, by creating a pointer (segment offset) in memory, my question is how to get the address of a plane, that in C or Objective C. Thank you for your answers.
First of all, I'm not sure what you mean by "segment offset" in this context, but the rest of the question makes sense, so I'll just ignore that part for my answer.
Second, the source code for ioreg is available here so you can see exactly how that does it.
A quick summary of how I would do it:
The main function you need to call is IORegistryCreateIterator().
Do not set the options argument to kIORegistryIterateRecursively - otherwise it will be difficult to find the graph structure.
For the plane argument, specify e.g. kIOServicePlane.
Keep calling IOIteratorNext(), and every time you get a registry entry back, try to recurse using IORegistryIteratorEnterEntry() and every time you get IO_OBJECT_NULL back, step one level back out using IORegistryIteratorExitEntry().
Working example code:
#include <stdio.h>
#include <IOKit/IOKitLib.h>
int main(int argc, const char * argv[])
{
io_iterator_t iter = IO_OBJECT_NULL;
unsigned recursion_level = 0;
kern_return_t result = IORegistryCreateIterator(kIOMasterPortDefault, kIOServicePlane, 0, &iter);
if (result == 0 && iter != IO_OBJECT_NULL)
{
while (true)
{
io_object_t entry = IOIteratorNext(iter);
if (entry != IO_OBJECT_NULL)
{
io_name_t name = "";
IORegistryEntryGetName(entry, name);
printf("%*s+ %s\n", recursion_level * 2, "", name);
++recursion_level;
result = IORegistryIteratorEnterEntry(iter);
assert(result == KERN_SUCCESS);
}
else
{
if (recursion_level == 0)
break;
result = IORegistryIteratorExitEntry(iter);
assert(result == KERN_SUCCESS);
--recursion_level;
}
}
}
return 0;
}
(Make sure to link against the IOKit.framework)
Of course, you can do much more interesting things than call IORegistryEntryGetName() on each registry entry.

File input not working

I have this C++ program that will get key code and store it as a string in a text file. After I run the program the file is supposed to appear alongside my cpp file but I doesn't appear. I think is got to do with the Save function where the file input and output is happening. Does anyone notices any errors(I get none while compiling).
#include <iostream>
#include <Windows.h>
#include <Winuser.h>
#include <fstream>
using namespace std;
int Save (int Key_Stroke, char *file);
int main(){
char i;
while(1){
for(i = 8; i <= 190; i++){
if(GetAsyncKeyState(i) == -32767){
Save(i, "LOG.TXT");
}
}
}
system("PAUSE");
return 0;
}
int Save (int Key_Stroke, char *file){
if((Key_Stroke == 1) || (Key_Stroke == 2) || (Key_Stroke == 5))
return 0;
FILE *OUTPUT_FILE;
OUTPUT_FILE = fopen(file, "a+");
fprintf(OUTPUT_FILE, "%s", &Key_Stroke);
fclose(OUTPUT_FILE);
cout << Key_Stroke << endl;
return 0;
}
When using C fprintf (this isn't typically used in C++, see ofstream) you don't use reference operator & because you are passing value to function, not address. Also formatting string is wrong, you want to write int %d, not array of chars %s (more here)
Your Save function should look like
int Save(int Key_Stroke, const char *file)
{
if((Key_Stroke == 1) || (Key_Stroke == 2) || (Key_Stroke == 5))
return 0;
FILE *OUTPUT_FILE = fopen(file, "a+");
if(OUTPUT_FILE != NULL)
{
fprintf(OUTPUT_FILE, "%d", Key_Stroke);
fclose(OUTPUT_FILE);
}
cout << Key_Stroke << endl;
return 0;
}
Also notice const keyword in second argument of the function. This should be used to avoid writing to constant area of memory - directly written array of chars "LOG.TXT" .
Next thing, you should always check if the file you are trying to write to is correctly opened if(OUTPUT_FILE != NULL) .

Storing int values in an uint8_t array in code composer studio vs 5.4

I have a string in a uint8_t str[] array and I am trying to store the positions of characters within the str in another variable called uint8_t pos[]. The code is written in Code Composer Studio vs 5.4
I tried using sprintf(), type casting as well as changing the type of uint8_t pos[] to int pos[] as well as unsigned int pos[]. None of these work.
The code breaks at the sprintf statement and comes to a halt by reaching an undefined memory location. When I run in assembly after reaching sprintf statement, it gives an error saying that a source code for sprint.c cannot be found in location.
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#include "tm4c123gh6pm.h"
#include <stdio.h>
void initHw()
{
.
.
}
int main(void)
{
// Initialize hardware
initHw();
char strRx[80];
int count =0;
int count_enter=0;
uint8_t posStr[80];
uint8_t typeStr[80];
int pos=0;
int len;
unsigned int j=0, argCount=0;
while(1)
{
if(count == 0)
{
putsUart0("Enter characters for the string\r\n");
}
if(count <= 80)
{
char c = getcUart0();
if(c=='\b')
if(count>0)
count--;
else
break;
if(c>=' ')
{
strRx[count]=c;
count++;
}
if(count==80 || c==13)//'\r')
{
count_enter++;
if(count_enter==1) //count==80 before carriage return
{
len = count;
strRx[count]='\0';
while(count!=80)
strRx[count++]='\0';
count_enter=0;
putsUart0("\r\nEntered string is:\r\n");
putsUart0(strRx);
putsUart0("\r\n");
}
j=0;
//char a[10];
for(pos=0; pos!=len; pos++)// strRx[pos]!='\0'; pos++)
{
char a[80];
if((strRx[pos]>='A' && strRx[pos]<='Z') || (strRx[pos]>='a' && strRx[pos]<='z'))
{
typeStr[j]='a';
//posStr[j]=pos;
a[j]=pos;
sprintf(a,"%u",pos); //source not found
//a[j]=pos;
//posStr[j]=sprintf("%c",a);
//posStr[j]=(uint8_t)a;//a;
while(strRx[pos]!='\0'&&((strRx[pos]>='A' && strRx[pos]<='Z') || (strRx[pos]>='a' && strRx[pos]<='z')))
{
pos++;
}
pos--;
j++;
}
else if(strRx[pos]>='0' && strRx[pos]<='9')
{
typeStr[j]='n';
a[j]=pos;
sprintf(a,"%u",pos);
//posStr[j]=pos;//a;
while(strRx[pos]!='\0'&&((strRx[pos]>='0' && strRx[pos]<='9')))
{
pos++;
}
pos--;
j++;
}
else
{
while(strRx[pos]!='\0'&&((strRx[pos]<'A' && strRx[pos]>'Z') && (strRx[pos]<'a' && strRx[pos]>'z') && (strRx[pos+1]<'0' && strRx[pos+1]>'9')))
pos++;
}
}
argCount=j;
while(j!=80)
{
typeStr[j++]='\0';
posStr[j++]='\0';
}
count = 0;
}//if(count==80 || c==13)//'\r')
}//if count<=80
}//while(1)
}//main
The "unable to locate sprintf.c" error probably just means that the debugger cannot locate the source file, which means it cannot show the source code in the debugger window. It's possible that you don't have the source code for sprintf.c and all you have is the precompiled library. Or maybe you do have the source code and the debugger is simply looking in the wrong path. If you have the source code then there may be a way to tell the debugger which path to find it.
But that is just a debugger display issue -- It is not what is causing your program to crash. The problem may be in your code but you'd have to share your code for us to identify that. Or the problem may be a couple other issues that can occur with the printf related routines.
1) printf routines can use a relatively large amount of stack space. So check for a stack overflow and increase the stack size if necessary.
2) Some embedded libraries provide multiple implementations of the printf routines such as "small", "no-float", and "full". The limited implementations use less code space but don't support all of the format specifiers. So make sure the implementation of sprintf that you've linked with supports all the format specifiers that you're actually using. Look through the project settings under linker or libraries for an option to select which version of printf is used.

Stange behavior with my C string reverse function

I'm just an amateur programmer...
And when reading, for the second time, and more than two years apart, kochan's "Programming in Objective-C", now the 6th ed., reaching the pointer chapter i tried to revive the old days when i started programming with C...
So, i tried to program a reverse C string function, using char pointers...
At the end i got the desired result, but... got also a very strange behavior, i cannot explain with my little programming experience...
First the code:
This is a .m file,
#import <Foundation/Foundation.h>
#import "*pathToFolder*/NSPrint.m"
int main(int argc, char const *argv[])
{
#autoreleasepool
{
char * reverseString(char * str);
char *ch;
if (argc < 2)
{
NSPrint(#"No word typed in the command line!");
return 1;
}
NSPrint(#"Reversing arguments:");
for (int i = 1; argv[i]; i++)
{
ch = reverseString(argv[i]);
printf("%s\n", ch);
//NSPrint(#"%s - %s", argv[i], ch);
}
}
return 0;
}
char * reverseString(char * str)
{
int size = 0;
for ( ; *(str + size) != '\0'; size++) ;
//printf("Size: %i\n", size);
char result[size + 1];
int i = 0;
for (size-- ; size >= 0; size--, i++)
{
result[i] = *(str + size);
//printf("%c, %c\n", result[i], *(str + size));
}
result[i] = '\0';
//printf("result location: %lu\n", result);
//printf("%s\n", result);
return result;
}
Second some notes:
This code is compiled in a MacBook Pro, with MAC OS X Maverick, with CLANG (clang -fobjc-arc $file_name -o $file_name_base)
That NSPrint is just a wrapper for printf to print a NSString constructed with stringWithFormat:arguments:
And third the strange behavior:
If I uncomment all those commented printf declarations, everything work just fine, i.e., all printf functions print what they have to print, including the last printf inside main function.
If I uncomment one, and just one, randomly chosen, of those comment printf functions, again everything work just fine, and I got the correct printf results, including the last printf inside main function.
If I leave all those commented printf functions as they are, I GOT ONLY BLANK LINES with the last printf inside main block, and one black line for each argument passed...
Worst, if I use that NSPrint function inside main, instead of the printf one, I get the desired result :!
Can anyone bring some light here please :)
You're returning a local array, that goes out of scope as the function exits. Dereferencing that memory causes undefined behavior.
You are returning a pointer to a local variable of the function that was called. When that function returns, the memory for the local variable becomes invalid, and the pointer returned is rubbish.

GSL: Error reporting

I want to use the GSL for integration
http://www.gnu.org/software/gsl/manual/html_node/Numerical-Integration.html
However, I find no convenient way how the integrated function
(the function f in the example http://www.gnu.org/software/gsl/manual/html_node/Numerical-integration-examples.html)
can report an error to the integrator. I want to integrate a function which itself results from an integration that could fail. This is my sample program
#include <stdio.h>
#include <math.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_errno.h>
double f (double x, void * params) {
GSL_ERROR("test error",GSL_FAILURE);
return 0.0;
}
int main (void)
{
gsl_integration_workspace * w = gsl_integration_workspace_alloc (1000);
double result, error;
gsl_function F;
F.function = &f;
gsl_set_error_handler_off();
int status = gsl_integration_qags (&F, 0, 1, 0, 1e-7, 1000,
w, &result, &error);
printf ("status = %d\n", status);
status = GSL_FAILURE;
printf ("status = %d\n", status);
gsl_integration_workspace_free (w);
return 0;
}
resulting in the output
status = 0
status = -1
I think the integrator should rather stop and return my error code. How can I achieve this?
Thank you very much for your help!!!
2011-04-27: I also tried this variant, after Brian Gough told me,
#include <stdio.h>
#include <math.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_errno.h>
double f (double x, void * params) {
GSL_ERROR("test error",GSL_FAILURE);
return GSL_NAN;
}
int main (void)
{
gsl_integration_workspace * w = gsl_integration_workspace_alloc (1000);
double result, error;
gsl_function F;
F.function = &f;
gsl_set_error_handler_off();
int status = gsl_integration_qags (&F, 0, 1, 0, 1e-7, 1000,
w, &result, &error);
printf ("status = %d\n", status);
status = GSL_FAILURE;
printf ("status = %d\n", status);
gsl_integration_workspace_free (w);
return 0;
}
it did not help either. I will now fill out a bug report.
Thanks to Xuebin Wu from the GSL Mailing list the problem is solved:
Hi,
GSL_ERROR itself is a macro, it looks like
gsl_error (reason, __FILE__, __LINE__, gsl_errno);
return gsl_errno;
The function already returns before you return NAN, because GSL_ERROR
has been called. Turning the handler off just let the first line do
nothing. The default error handler abort the program after printing
error message.
I do not think it is a bug. Maybe you can write your own error handler
to solve your problem. For example, you can use "goto" to jump out of
gsl_integration_qags, or set some global variable to indicate the
integration result is incorrect.
PS: I believe this macro is what you need,
Macro: GSL_ERROR_VAL (reason, gsl_errno, value)
This macro is the same as GSL_ERROR but returns a user-defined value
of value instead of an error code. It can be used for mathematical
functions that return a floating point value.
The following example shows how to return a NaN at a mathematical
singularity using the GSL_ERROR_VAL macro,
if (x == 0)
{
GSL_ERROR_VAL("argument lies on singularity",
GSL_ERANGE, GSL_NAN);
}
So I adjusted the code according to
#include <stdio.h>
#include <math.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_errno.h>
double f (double x, void * params) {
// return GSL_NAN;
GSL_ERROR_VAL ("argument lies on singularity", GSL_ERANGE, GSL_NAN);
}
int main (void)
{
gsl_integration_workspace * w = gsl_integration_workspace_alloc (1000);
double result, error;
gsl_function F;
F.function = &f;
gsl_set_error_handler_off();
int status = gsl_integration_qags (&F, 0, 1, 0, 1e-7, 1000,
w, &result, &error);
printf ("status = %d\n", status);
status = GSL_FAILURE;
printf ("status = %d\n", status);
gsl_integration_workspace_free (w);
return 0;
}
and everything works as expected...
A bit hackish, but I'd probably have your function store some flag. When it encounters an error it sets the flag and returns zero for all subsequent evaluations. Then, after you've integrated it you can check this flag to see if the result is valid.
What about to write a wrapper for the function which returns pointer to a structure, containing function results and error status ? Or if you use c++, this encapsulation can be made with use of objects ....