Search Results

Search found 1848 results on 74 pages for 'printf'.

Page 20/74 | < Previous Page | 16 17 18 19 20 21 22 23 24 25 26 27  | Next Page >

  • Using popen() to invoke a shell command?

    - by Anvar
    When running the following code through xcode I get inconsistent behavior. Sometimes it prints the git version correctly, other times it doesn't print anything. The return code from the shell command is always 0 though. Any ideas on why this might be? What am I doing wrong? #define BUFFER_SIZE 256 int main (int argc, const char * argv[]) { FILE *fpipe; char *command="/opt/local/bin/git --version"; char line[BUFFER_SIZE]; if ( !(fpipe = (FILE*)popen(command, "r")) ) { // If fpipe is NULL perror("Problems with pipe"); exit(1); } while ( fgets( line, sizeof(char) * BUFFER_SIZE, fpipe)) { // Inconsistent (happens sometimes) printf("READING LINE"); printf("%s", line); } int status = pclose(fpipe); if (status != 0) { // Never happens printf("Strange error code: %d", status); } return 0; }

    Read the article

  • what wrong are there

    - by gcc
    int main(void) { char *tutar[100][20],temp; int i; int n; i=0; while(temp!='x') { scanf("%c",&temp); tutar[i]=malloc(sizeof(int)); tutar[i]=temp; ++i; } n =i; for(i=0;i<=n;++i) { printf(" %c ",*tutar[i]); } printf("\n\n"); /*for(i=0;i<=n;++i) { printf("%d",atoi(*tutar[i])); } */

    Read the article

  • "exception at 0x53C227FF (msvcr110d.dll)" with SOIL library

    - by Sean M.
    I'm creating a game in C++ using OpenGL, and decided to go with the SOIL library for image loading, as I have used it in the past to great effect. The problem is, in my newest game, trying to load an image with SOIL throws the following runtime error: This error points to this part: // SOIL.c int query_NPOT_capability( void ) { /* check for the capability */ if( has_NPOT_capability == SOIL_CAPABILITY_UNKNOWN ) { /* we haven't yet checked for the capability, do so */ if( (NULL == strstr( (char const*)glGetString( GL_EXTENSIONS ), "GL_ARB_texture_non_power_of_two" ) ) ) //############ it points here ############// { /* not there, flag the failure */ has_NPOT_capability = SOIL_CAPABILITY_NONE; } else { /* it's there! */ has_NPOT_capability = SOIL_CAPABILITY_PRESENT; } } /* let the user know if we can do non-power-of-two textures or not */ return has_NPOT_capability; } Since it points to the line where SOIL tries to access the OpenGL extensions, I think that for some reason SOIL is trying to load the texture before an OpenGL context is created. The problem is, I've gone through the entire solution, and there is only one place where SOIL has to load a texture, and it happens long after the OpenGL context is created. This is the part where it loads the texture... //Init glfw if (!glfwInit()) { fprintf(stderr, "GLFW Initialization has failed!\n"); exit(EXIT_FAILURE); } printf("GLFW Initialized.\n"); //Process the command line arguments processCmdArgs(argc, argv); //Create the window glfwWindowHint(GLFW_SAMPLES, g_aaSamples); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); g_mainWindow = glfwCreateWindow(g_screenWidth, g_screenHeight, "Voxel Shipyard", g_fullScreen ? glfwGetPrimaryMonitor() : nullptr, nullptr); if (!g_mainWindow) { fprintf(stderr, "Could not create GLFW window!\n"); closeOGL(); exit(EXIT_FAILURE); } glfwMakeContextCurrent(g_mainWindow); printf("Window and OpenGL rendering context created.\n"); //Create the internal rendering components prepareScreen(); //Init glew glewExperimental = GL_TRUE; int err = glewInit(); if (err != GLEW_OK) { fprintf(stderr, "GLEW initialization failed!\n"); fprintf(stderr, "%s\n", glewGetErrorString(err)); closeOGL(); exit(EXIT_FAILURE); } printf("GLEW initialized.\n"); <-- Sucessfully creates an OpenGL context //Initialize the app g_app = new App(); g_app->PreInit(); g_app->Init(); g_app->PostInit(); <-- Loads the texture (after the context is created) ...and debug printing to the console CONFIRMS that the OpenGL context was created before the texture loading was attempted. So my question is if anyone is familiar with this specific error, or knows if there is a specific instance as to why SOIL would think OpenGL isn't initialized yet.

    Read the article

  • What is this code?

    - by Aerovistae
    This is from the Evolution of a Programmer "joke", at the "Master Programmer" level. It seems to be C++, but I don't know what all this bloated extra stuff is, nor did any Google searches turn up anything except the joke I took it from. Can anyone tell me more about what I'm reading here? [ uuid(2573F8F4-CFEE-101A-9A9F-00AA00342820) ] library LHello { // bring in the master library importlib("actimp.tlb"); importlib("actexp.tlb"); // bring in my interfaces #include "pshlo.idl" [ uuid(2573F8F5-CFEE-101A-9A9F-00AA00342820) ] cotype THello { interface IHello; interface IPersistFile; }; }; [ exe, uuid(2573F890-CFEE-101A-9A9F-00AA00342820) ] module CHelloLib { // some code related header files importheader(<windows.h>); importheader(<ole2.h>); importheader(<except.hxx>); importheader("pshlo.h"); importheader("shlo.hxx"); importheader("mycls.hxx"); // needed typelibs importlib("actimp.tlb"); importlib("actexp.tlb"); importlib("thlo.tlb"); [ uuid(2573F891-CFEE-101A-9A9F-00AA00342820), aggregatable ] coclass CHello { cotype THello; }; }; #include "ipfix.hxx" extern HANDLE hEvent; class CHello : public CHelloBase { public: IPFIX(CLSID_CHello); CHello(IUnknown *pUnk); ~CHello(); HRESULT __stdcall PrintSz(LPWSTR pwszString); private: static int cObjRef; }; #include <windows.h> #include <ole2.h> #include <stdio.h> #include <stdlib.h> #include "thlo.h" #include "pshlo.h" #include "shlo.hxx" #include "mycls.hxx" int CHello:cObjRef = 0; CHello::CHello(IUnknown *pUnk) : CHelloBase(pUnk) { cObjRef++; return; } HRESULT __stdcall CHello::PrintSz(LPWSTR pwszString) { printf("%ws\n", pwszString); return(ResultFromScode(S_OK)); } CHello::~CHello(void) { // when the object count goes to zero, stop the server cObjRef--; if( cObjRef == 0 ) PulseEvent(hEvent); return; } #include <windows.h> #include <ole2.h> #include "pshlo.h" #include "shlo.hxx" #include "mycls.hxx" HANDLE hEvent; int _cdecl main( int argc, char * argv[] ) { ULONG ulRef; DWORD dwRegistration; CHelloCF *pCF = new CHelloCF(); hEvent = CreateEvent(NULL, FALSE, FALSE, NULL); // Initialize the OLE libraries CoInitiali, NULL); // Initialize the OLE libraries CoInitializeEx(NULL, COINIT_MULTITHREADED); CoRegisterClassObject(CLSID_CHello, pCF, CLSCTX_LOCAL_SERVER, REGCLS_MULTIPLEUSE, &dwRegistration); // wait on an event to stop WaitForSingleObject(hEvent, INFINITE); // revoke and release the class object CoRevokeClassObject(dwRegistration); ulRef = pCF->Release(); // Tell OLE we are going away. CoUninitialize(); return(0); } extern CLSID CLSID_CHello; extern UUID LIBID_CHelloLib; CLSID CLSID_CHello = { /* 2573F891-CFEE-101A-9A9F-00AA00342820 */ 0x2573F891, 0xCFEE, 0x101A, { 0x9A, 0x9F, 0x00, 0xAA, 0x00, 0x34, 0x28, 0x20 } }; UUID LIBID_CHelloLib = { /* 2573F890-CFEE-101A-9A9F-00AA00342820 */ 0x2573F890, 0xCFEE, 0x101A, { 0x9A, 0x9F, 0x00, 0xAA, 0x00, 0x34, 0x28, 0x20 } }; #include <windows.h> #include <ole2.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include "pshlo.h" #include "shlo.hxx" #include "clsid.h" int _cdecl main( int argc, char * argv[] ) { HRESULT hRslt; IHello *pHello; ULONG ulCnt; IMoniker * pmk; WCHAR wcsT[_MAX_PATH]; WCHAR wcsPath[2 * _MAX_PATH]; // get object path wcsPath[0] = '\0'; wcsT[0] = '\0'; if( argc > 1) { mbstowcs(wcsPath, argv[1], strlen(argv[1]) + 1); wcsupr(wcsPath); } else { fprintf(stderr, "Object path must be specified\n"); return(1); } // get print string if(argc > 2) mbstowcs(wcsT, argv[2], strlen(argv[2]) + 1); else wcscpy(wcsT, L"Hello World"); printf("Linking to object %ws\n", wcsPath); printf("Text String %ws\n", wcsT); // Initialize the OLE libraries hRslt = CoInitializeEx(NULL, COINIT_MULTITHREADED); if(SUCCEEDED(hRslt)) { hRslt = CreateFileMoniker(wcsPath, &pmk); if(SUCCEEDED(hRslt)) hRslt = BindMoniker(pmk, 0, IID_IHello, (void **)&pHello); if(SUCCEEDED(hRslt)) { // print a string out pHello->PrintSz(wcsT); Sleep(2000); ulCnt = pHello->Release(); } else printf("Failure to connect, status: %lx", hRslt); // Tell OLE we are going away. CoUninitialize(); } return(0); }

    Read the article

  • Simple Scripting for your Exalogic Storage

    - by Trond Strømme
    As part of my job in Oracle ACS (Advanced Customer Services) I'm handling lots of different systems and customers. Among the recent systems I worked with have been Oracle's Exalogic engineered systems. One of the things I'd never had much exposure to as a system developer/architect/middleware guy/Java dude has been storage; outside of consuming it for my photography needs.. Well, I'm always ready for a new challenge... I'd downloaded the 7000 series storage simulator when it was released in the good old Sun days, found it fun and instructive to play around with, but as I never touched storage in any way (besides consuming it..) I forgot about it. A couple of years ago when I started working with Exalogic engineered systems it again came into light as an invaluable learning and testing tool for the embedded storage in an Exalogic;  Oracle's Sun ZFS Storage 7320 Appliance.  aaaanyway... I've been "booted" into a part-time role as the interim storage/system admin/middleware/Java guy for a client and found I needed to create the occasional report or summary or whatever.. of what's using the storage in the 7320 (as default configured for an Exalogic, 40T of disk in a mirrored configuration, yielding 18T of actual space.) Reading the nice documentation and some articles on the Oracle Technology Network I saw great possibilities with the embedded ECMAScript3/JavaScript engine in the 7000 series.  In my personal opinion anyone who's dealing with Exalogic administration, or exposed to any of the 7000 series of storage appliances and servers that Oracle offers should have a VirtualBox instance of it kicking around. For development and testing it's a fantastic tool. (It can save you from explaining (most) of the embarrassing FAILS you can do if you test something in a production system to your management...) So download, and install.  A small sidestep, if after firing up the 7000 series simulator in VirtualBox you've forgotten what it's IP address is, the following will sort you out if you log in directly via the running VirtualBox VM. So in my case I can ssh to 192.168.56.101 or point a browser to https://192.168.56.101:215 to log into the storage appliance. One simple way of executing a script on the 7320 is to ssh to the device and redirecting a file with the script in it to ssh. ssh [email protected] < myscript.js One question I got from my client and the people who will take over the systems was: "how can we see the quotas and allocations for all projects/shares in one easy go so we don't have to go navigating around in the BUI for all the hundreds of shares the 7320 is hosting just to check if anything is running dry?" Easy! JavaScript time, VirtualBox and emacs! //NOTE! this script is available 'as is' It has ben run on a couple of 7320's, (running 2010.08.17.3.0,1-1.25 & // 2011.04.24.1.0,1-1.8) a 7420 and the VB image, but I personally //offer no guarantee whatsoever that it won't make your server topple, catch fire or in any way go pear shaped.. //run at your own risk or learn from my code and or mistakes.. script run('cd /'); run('shares'); //get all projects: proj = list(); function spaceToGig(bytes){ return bytes/1073741824; //convert bytes to GB } function fullInPercent(quota, space_data){ tmp = (space_data/quota)*100; return tmp; } //print header, slightly good looking printf(" %s/%-15s %8s(GB) %7s(GB) %5s(GB) %7s(GB) %3s\n","Project", "Share","Quota","Ref", "Snap", "Total","%full"); printf("-------------------------------------------------------------------------------\n") //for each project, get all shares. check for quota and calculate percentage and human readable figures.. for (i=0;i<proj.length;i++){ run('select ' + proj[i]); //get all shares for a project var pshares = list(); //for each share get quota properties for (j=0;j<pshares.length;j++){ run('select ' + pshares[j]); quota = get('quota'); //properties associated with a share or inherited from a project spaceData = get('space_data'); spaceSnap = get('space_snapshots'); spaceTotal = get('space_total'); if(quota>0){ //has quota printf(" %s/%-15s \t%4.2fGB\t%.2fGB\t%.2fGB\t%.2fGB\t%5.2f%%\n",proj[i], pshares[j],spaceToGig(quota),spaceToGig(spaceData),spaceToGig(spaceSnap),spaceToGig(spaceTotal),fullInPercent(quota,spaceTotal)); }else{ //no quota printf(" %s/%-15s \t%8s\t%.2fGB\t%.2fGB\t%.2fGB\t%s\n",proj[i],pshares[j], "N/A", spaceToGig(spaceData),spaceToGig(spaceSnap),spaceToGig(spaceTotal),"N/A"); } run('cd ..'); } run('done'); } The resulting output should look something like this: Project/Share Quota(GB) Ref(GB) Snap(GB) Total(GB) %full ------------------------------------------------------------------------------- ACSExalogicSystem/domains N/A 0.04GB 0.00GB 0.04GB N/A ACSExalogicSystem/logs N/A 0.01GB 0.00GB 0.01GB N/A ACSExalogicSystem/nodemgrs N/A 0.00GB 0.00GB 0.00GB N/A ACSExalogicSystem/stores N/A 0.04GB 0.00GB 0.04GB N/A ***_dev/FMW_***_1 133GB 4.24GB 0.01GB 4.25GB 3.19% ***_dev/FMW_***_2 N/A 4.25GB 0.01GB 4.26GB N/A ***_dev/applications 10GB 0.00GB 0.00GB 0.00GB 0.00% ***_dev/domains 50GB 10.75GB 3.55GB 14.30GB 28.61% ***_dev/logs 20GB 0.32GB 0.01GB 0.33GB 1.66% ***_dev/softwaredepot 20GB 4.15GB 0.00GB 4.15GB 20.73% ***_dev/stores 20GB 0.01GB 0.00GB 0.01GB 0.05% ###_dev/FMW_###_1 400GB 17.63GB 0.12GB 17.75GB 4.44% ###_dev/applications N/A 0.00GB 0.00GB 0.00GB N/A ###_dev/domains 120GB 14.21GB 5.53GB 19.74GB 16.45% ###_dev/logs 15GB 0.00GB 0.00GB 0.00GB 0.00% ###_dev/softwaredepot 250GB 73.55GB 0.02GB 73.57GB 29.43% …snip My apologies if the output is a bit mis-aligned here and there, I only bothered making it look good, not perfect :/ I also removed some of the project names (*,#)

    Read the article

  • Pointer initialization doubt

    - by Jestin Joy
    We could initialize a character pointer like this in C. char *c="test"; Where c points to the first character(t). But when I gave code like below. It gives segmentation fault. #include<stdio.h> #include<stdlib.h> main() { int *i; *i=0; printf("%d",*i); } But when I give #include<stdio.h> #include<stdlib.h> main() { int *i; i=(int *)malloc(2); *i=0; printf("%d",*i); } It works( gives output 0). Also when I give malloc(0), It also works( gives output 0). Please tell what is happening

    Read the article

  • Problems Rendering Text in OpenGL Using FreeType

    - by Sean M.
    I've been following both the FreeType2 tutorial and the WikiBooks tuorial, trying to combine things from them both in order to load and render fonts using the FreeType library. I used the font loading code from the FreeType2 tutorial and tried to implement the rendering code from the wikibooks tutorial (tried being the keyword as I'm still trying to learn model OpenGL, I'm using 3.2). Everything loads correctly and I have the shader program to render the text with working, but I can't get the text to render. I'm 99% sure that it has something to do with how I cam passing data to the shader, or how I set up the screen. These are the code segments that handle OpenGL initialization, as well as Font initialization and rendering: //Init glfw if (!glfwInit()) { fprintf(stderr, "GLFW Initialization has failed!\n"); exit(EXIT_FAILURE); } printf("GLFW Initialized.\n"); //Process the command line arguments processCmdArgs(argc, argv); //Create the window glfwWindowHint(GLFW_SAMPLES, g_aaSamples); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); g_mainWindow = glfwCreateWindow(g_screenWidth, g_screenHeight, "Voxel Shipyard", g_fullScreen ? glfwGetPrimaryMonitor() : nullptr, nullptr); if (!g_mainWindow) { fprintf(stderr, "Could not create GLFW window!\n"); closeOGL(); exit(EXIT_FAILURE); } glfwMakeContextCurrent(g_mainWindow); printf("Window and OpenGL rendering context created.\n"); glClearColor(0.2f, 0.2f, 0.2f, 1.0f); //Are these necessary for Modern OpenGL (3.0+)? glViewport(0, 0, g_screenWidth, g_screenHeight); glOrtho(0, g_screenWidth, g_screenHeight, 0, -1, 1); //Init glew int err = glewInit(); if (err != GLEW_OK) { fprintf(stderr, "GLEW initialization failed!\n"); fprintf(stderr, "%s\n", glewGetErrorString(err)); closeOGL(); exit(EXIT_FAILURE); } printf("GLEW initialized.\n"); Here is the font file (it's slightly too big to post): CFont.h/CFont.cpp Here is the solution zipped up: [solution] (https://dl.dropboxusercontent.com/u/36062916/VoxelShipyard.zip), if anyone feels they need the entire solution. If anyone could take a look at the code, it would be greatly appreciated. Also if someone has a tutorial that is a little more user friendly, that would also be appreciated. Thanks.

    Read the article

  • wordpress woocommerce php variable usage %1$s

    - by tech
    I am using wordpress with woocommerce and I am trying to manipulate a copy of myaccount.php The default code uses some variables of some sort that I am not familiar with nor have I been able to find documentation on. The variables in question are %1$s, %2$s and %s <p class="myaccount_user"> <?php printf( __( 'Hello <strong>%1$s</strong> (not %1$s? <a href="%2$s">Sign out</a>).', 'woocommerce' ) . ' ', $current_user->display_name, wp_logout_url( get_permalink( wc_get_page_id( 'myaccount' ) ) ) ); ?> <?php printf( __( 'From this page you can view your recent orders, manage your shipping and billing addresses and <a href="%s">edit your password and account details</a>.', 'woocommerce' ), wc_customer_edit_account_url() ); ?> </p> How can I identify the variables, what they represent and how to use them? Thank you.

    Read the article

  • Given a string of letters from alphabet insert frequency of each character in the string.in O(n) time and O(1) space [on hold]

    - by learner
    Below is my attempt void str_freq(char *str, int len) { char c; int cnt=0; c=str[0]; int i,j=0; for(i=0;i<len;i++) { if(c==str[i]) { cnt++; } else { c = str[i]; // printf(" %d ",cnt); str[j] = str[i-1]; str[j+1] = (char)(((int)'0')+cnt); j++; cnt=0; } } str[j+1]='\0'; printf("%s",str); } int main() { char str[] = "aaabbccccdeffgggg"; int length=strlen(str); str_freq(str,length); } I am getting wrong answer abcdef1 instead of a3b2c4d1e1f2g4. Please let me know where I am going wrong.

    Read the article

  • (SOLVED) Problems Rendering Text in OpenGL Using FreeType

    - by Sean M.
    I've been following both the FreeType2 tutorial and the WikiBooks tuorial, trying to combine things from them both in order to load and render fonts using the FreeType library. I used the font loading code from the FreeType2 tutorial and tried to implement the rendering code from the wikibooks tutorial (tried being the keyword as I'm still trying to learn model OpenGL, I'm using 3.2). Everything loads correctly and I have the shader program to render the text with working, but I can't get the text to render. I'm 99% sure that it has something to do with how I cam passing data to the shader, or how I set up the screen. These are the code segments that handle OpenGL initialization, as well as Font initialization and rendering: //Init glfw if (!glfwInit()) { fprintf(stderr, "GLFW Initialization has failed!\n"); exit(EXIT_FAILURE); } printf("GLFW Initialized.\n"); //Process the command line arguments processCmdArgs(argc, argv); //Create the window glfwWindowHint(GLFW_SAMPLES, g_aaSamples); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); g_mainWindow = glfwCreateWindow(g_screenWidth, g_screenHeight, "Voxel Shipyard", g_fullScreen ? glfwGetPrimaryMonitor() : nullptr, nullptr); if (!g_mainWindow) { fprintf(stderr, "Could not create GLFW window!\n"); closeOGL(); exit(EXIT_FAILURE); } glfwMakeContextCurrent(g_mainWindow); printf("Window and OpenGL rendering context created.\n"); glClearColor(0.2f, 0.2f, 0.2f, 1.0f); //Are these necessary for Modern OpenGL (3.0+)? glViewport(0, 0, g_screenWidth, g_screenHeight); glOrtho(0, g_screenWidth, g_screenHeight, 0, -1, 1); //Init glew int err = glewInit(); if (err != GLEW_OK) { fprintf(stderr, "GLEW initialization failed!\n"); fprintf(stderr, "%s\n", glewGetErrorString(err)); closeOGL(); exit(EXIT_FAILURE); } printf("GLEW initialized.\n"); Here is the font file (it's slightly too big to post): CFont.h/CFont.cpp Here is the solution zipped up: [solution] (https://dl.dropboxusercontent.com/u/36062916/VoxelShipyard.zip), if anyone feels they need the entire solution. If anyone could take a look at the code, it would be greatly appreciated. Also if someone has a tutorial that is a little more user friendly, that would also be appreciated. Thanks.

    Read the article

  • When attaching AI to a vehicle should I define all steps or try Line of Sight?

    - by ThorDivDev
    This problem is related to an intersection simulation I am building for university. I will try to make it as general as possible. I am trying to assign AI to a vehicle using the JMonkeyEngine platform. AIGama_JmonkeyEngine explains that if you wish to create a car that follows a path you can define the path in steps. If there was no physics attached whatsoever then all you need to do is define the x,y,z values of where you want the object to appear in all subsequent steps. I am attaching the vehicleControl that implements jBullet. In this case the author mentions that I would need to define the steering and accelerating behaviors at each step. I was trying to use ghost controls that represented waypoints and when on colliding the car would decide what to do next like stopping at a red light. This didn't work so well. Car doesn't face right. public void update(float tpf) { Vector3f currentPos = aiVehicle.getPhysicsLocation(); Vector3f baseforwardVector = currentPos.clone(); Vector3f forwardVector; Vector3f subsVector; if (currentState == ObjectState.Running) { aiVehicle.accelerate(-800); } else if (currentState == ObjectState.Seeking) { baseforwardVector = baseforwardVector.normalize(); forwardVector = aiVehicle.getForwardVector(baseforwardVector); subsVector = pointToSeek.subtract(currentPos.clone()); System.out.printf("baseforwardVector: %f, %f, %f\n", baseforwardVector.x, baseforwardVector.y, baseforwardVector.z); System.out.printf("subsVector: %f, %f, %f\n", subsVector.x, subsVector.y, subsVector.z); System.out.printf("ForwardVector: %f, %f, %f\n", forwardVector.x, forwardVector.y, forwardVector.z); if (pointToSeek != null && pointToSeek.x + 3 >= currentPos.x && pointToSeek.x - 3 <= currentPos.x) { aiVehicle.steer(0.0f); aiVehicle.accelerate(-40); } else if (pointToSeek != null && pointToSeek.x > currentPos.x) { aiVehicle.steer(-0.5f); aiVehicle.accelerate(-40); } else if (pointToSeek != null && pointToSeek.x < currentPos.x) { aiVehicle.steer(0.5f); aiVehicle.accelerate(-40); } } else if (currentState == ObjectState.Stopped) { aiVehicle.accelerate(0); aiVehicle.brake(40); } }

    Read the article

  • Concat wchar_t Unicode strings in C?

    - by Doori Bar
    I'm a beginner, I play with FindFirstFileW() of the winapi - C. The unicoded path is: " \\?\c:\Français\", and I would like to concat "*" to this path of type wchar_t (then I will use it as an arg for FindFirstFileW()). I made two test cases of mine, the first is ansi_string() which seem to work fine, the second is unicode_string() - which I don't quite understand how should I concat the additional "*" char to the unicoded path. I write the strings to a file, because I'm not able to print Unicoded characters to stdout. Note: my goal is to learn, which means I'll appreciate guidance and references to the appropriate resources regards my scenario, I'm very much a beginner and this is my first attempt with Unicode. Thanks, Doori Bar #include <stdio.h> #include <stdlib.h> #include <wchar.h> #include <string.h> #include <errno.h> void *error_malloc(int size); void ansi_string(char **str1, char **str2); void unicode_string(wchar_t **wstr1, wchar_t **wstr2); void unicode_string(wchar_t **wstr1, wchar_t **wstr2) { /* assign wstr1 with the path: \\?\c:\Français\ */ *wstr1 = error_malloc((wcslen(L"\\\\?\\c:\\Français\\")+1) *sizeof(**wstr1)); wcscpy(*wstr1,L"\\\\?\\c:\\Français\\"); /* concat wstr1+"*" , assign wstr2 with: \\?\c:\Français\* */ *wstr2 = error_malloc((wcslen(*wstr1) + 1 + 1) * sizeof(**wstr1)); /* swprintf(*wstr2,"%ls*",*wstr1); */ /* how should I concat wstr1+"*"? */ wcscpy(*wstr2,L"\\\\?\\c:\\Français\\"); } void ansi_string(char **str1, char **str2) { /* assign str1 with the path: c:\English\ */ *str1 = error_malloc(strlen("c:\\English\\") + 1); strcpy(*str1,"c:\\English\\"); /* concat str1+"*" , assign str2 with: c:\English\* */ *str2 = error_malloc(strlen(*str1) + 1 + 1); sprintf(*str2,"%s*",*str1); } void *error_malloc(int size) { void *ptr; int errornumber; if ((ptr = malloc(size)) == NULL) { errornumber = errno; fprintf(stderr,"Error: malloc(): %d; Error Message: %s;\n", errornumber,strerror(errornumber)); exit(1); } return ptr; } int main(void) { FILE *outfile; char *str1; char *str2; wchar_t *wstr1; wchar_t *wstr2; if ((outfile = fopen("out.bin","w")) == NULL) { printf("Error: fopen failed."); return 1; } ansi_string(&str1,&str2); fwrite(str2, sizeof(*str2), strlen(str2), outfile); printf("strlen: %d\n",strlen(str2)); printf("sizeof: %d\n",sizeof(*str2)); free(str1); free(str2); unicode_string(&wstr1,&wstr2); fwrite(wstr2, sizeof(*wstr2), wcslen(wstr2), outfile); printf("wcslen: %d\n",wcslen(wstr2)); printf("sizeof: %d\n",sizeof(*wstr2)); free(wstr1); free(wstr2); fclose(outfile); return 0; }

    Read the article

  • seg fault caused by malloc and sscanf in a function

    - by Framester
    Hi, I want to open a text file (see below), read the first int in every line and store it in an array, but I get an segmentation fault. I got rid of all gcc warnings, I read through several tutorials I found on the net and searched stackoverflow for solutions, but I could't make out, what I am doing wrong. It works when I have everything in the main function (see example 1), but not when I transfer it to second function (see example 2 further down). In example 2 I get, when I interpret gdb correctly a seg fault at sscanf (line,"%i",classes[i]);. I'm afraid, it could be something trivial, but I already wasted one day on it. Thanks in advance. [Example 1] Even though that works with everything in main: #include<stdio.h> #include<stdlib.h> #include<string.h> const int LENGTH = 1024; int main() { char *filename="somedatafile.txt"; int *classes; int lines; FILE *pfile = NULL; char line[LENGTH]; pfile=fopen(filename,"r"); int numlines=0; char *p; while(fgets(line,LENGTH,pfile)){ numlines++; } rewind(pfile); classes=(int *)malloc(numlines*sizeof(int)); if(classes == NULL){ printf("\nMemory error."); exit(1); } int i=0; while(fgets(line,LENGTH,pfile)){ printf("\n"); p = strtok (line," "); p = strtok (NULL, ", "); sscanf (line,"%i",&classes[i]); i++; } fclose(pfile); return 1; } [Example 2] This does not with the functionality transfered to a function: #include<stdio.h> #include<stdlib.h> #include<string.h> const int LENGTH = 1024; void read_data(int **classes,int *lines, char *filename){ FILE *pfile = NULL; char line[LENGTH]; pfile=fopen(filename,"r"); int numlines=0; char *p; while(fgets(line,LENGTH,pfile)){ numlines++; } rewind(pfile); * classes=(int *)malloc(numlines*sizeof(int)); if(*classes == NULL){ printf("\nMemory error."); exit(1); } int i=0; while(fgets(line,LENGTH,pfile)){ printf("\n"); p = strtok (line," "); p = strtok (NULL, ", "); sscanf (line,"%i",classes[i]); i++; } fclose(pfile); *lines=numlines; } int main() { char *filename="somedatafile.txt"; int *classes; int lines; read_data(&classes, &lines,filename) ; for(int i=0;i<lines;i++){ printf("\nclasses[i]=%i",classes[i]); } return 1; } [Content of somedatafile.txt] 50 21 77 0 28 0 27 48 22 2 55 0 92 0 0 26 36 92 56 4 53 0 82 0 52 -5 29 30 2 1 37 0 76 0 28 18 40 48 8 1 37 0 79 0 34 -26 43 46 2 1 85 0 88 -4 6 1 3 83 80 5 56 0 81 0 -4 11 25 86 62 4 55 -1 95 -3 54 -4 40 41 2 1 53 8 77 0 28 0 23 48 24 4 37 0 101 -7 28 0 64 73 8 1 ...

    Read the article

  • C - struct problems - writing

    - by Catarrunas
    Hello, I'm making a program in C, and I'mm having some troubles with memory, I think. So my problem is: I have 2 functions that return a struct. When I run only one function at a time I have no problem whatsoever. But when I run one after the other I always get an error when writting to the second struct. Function struct item* ReadFileBIN(char *name) -- reads a binary file. struct tables* getMesasInfo(char* Filename) -- reads a text file. My code is this: #include "stdafx.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> int numberOfTables=0; int numberOfItems=0; //struct tables* mesas; //struct item* Menu; typedef struct item{ char nome[100]; int id; float preco; }; typedef struct tables{ int id; int capacity; bool inUse; }; struct tables* getMesasInfo(char* Filename){ struct tables* mesas; char *c; int counter,numberOflines=0,temp=0; char *filename=Filename; FILE * G; G = fopen(filename,"r"); if (G==NULL){ printf("Cannot open file.\n"); } else{ while (!feof(G)){ fscanf(G, "%s", &c); numberOflines++; } fclose(G); } /* Memory allocate for input array */ mesas = (struct tables *)malloc(numberOflines* sizeof(struct tables*)); counter=0; G=fopen(filename,"r"); while (!feof(G)){ mesas[counter].id=counter; fscanf(G, "%d", &mesas[counter].capacity); mesas[counter].inUse= false; counter++; } fclose(G); numberOfTables = counter; return mesas; } struct item* ReadFileBIN(char *name) { int total=0; int counter; FILE *ptr_myfile; struct item my_record; struct item* Menu; ptr_myfile=fopen(name,"r"); if (!ptr_myfile) { printf("Unable to open file!"); } while (!feof(ptr_myfile)){ fread(&my_record,sizeof(struct item),1,ptr_myfile); total=total+1; } numberOfItems=total-1; Menu = (struct item *)calloc(numberOfItems , sizeof(struct item)); fseek(ptr_myfile, sizeof(struct item), SEEK_END); rewind(ptr_myfile); for ( counter=1; counter < total ; counter++) { fread(&my_record,sizeof(struct item),1,ptr_myfile); Menu[counter] = my_record; printf("Nome: %s\n",Menu[counter].nome); printf("ID: %d\n",Menu[counter].id); printf("Preco: %f\n",Menu[counter].preco); } fclose(ptr_myfile); return Menu; } int _tmain(int argc, _TCHAR* argv[]) { struct item* tt = ReadFileBIN("menu.dat"); struct tables* t = getMesasInfo("Capacity.txt"); getchar(); }** Thanks in advance.

    Read the article

  • C++ template function specialization using TCHAR on Visual Studio 2005

    - by Eli
    I'm writing a logging class that uses a templatized operator<< function. I'm specializing the template function on wide-character string so that I can do some wide-to-narrow translation before writing the log message. I can't get TCHAR to work properly - it doesn't use the specialization. Ideas? Here's the pertinent code: // Log.h header class Log { public: template <typename T> Log& operator<<( const T& x ); template <typename T> Log& operator<<( const T* x ); template <typename T> Log& operator<<( const T*& x ); ... } template <typename T> Log& Log::operator<<( const T& input ) { printf("ref"); } template <typename T> Log& Log::operator<<( const T* input ) { printf("ptr"); } template <> Log& Log::operator<<( const std::wstring& input ); template <> Log& Log::operator<<( const wchar_t* input ); And the source file // Log.cpp template <> Log& Log::operator<<( const std::wstring& input ) { printf("wstring ref"); } template <> Log& Log::operator<<( const wchar_t* input ) { printf("wchar_t ptr"); } template <> Log& Log::operator<<( const TCHAR*& input ) { printf("tchar ptr ref"); } Now, I use the following test program to exercise these functions // main.cpp - test program int main() { Log log; log << "test 1"; log << L"test 2"; std::string test3( "test3" ); log << test3; std::wstring test4( L"test4" ); log << test4; TCHAR* test5 = L"test5"; log << test4; } Running the above tests reveals the following: // Test results ptr wchar_t ptr ref wstring ref ref Unfortunately, that's not quite right. I'd really like the last one to be "TCHAR", so that I can convert it. According to Visual Studio's debugger, the when I step in to the function being called in test 5, the type is wchar_t*& - but it's not calling the appropriate specialization. Ideas? I'm not sure if it's pertinent or not, but this is on a Windows CE 5.0 device.

    Read the article

  • When I try to redefine a variable, I get an index out of bounds error

    - by user2770254
    I'm building a program to act as a calculator with memory, so you can give variables and their values. Whenever I'm trying to redefine a variable, a = 5, to a = 6, I get an index out of bounds error. public static void main(String args[]) { LinkedHashMap<String,Integer> map = new LinkedHashMap<String,Integer>(); Scanner scan = new Scanner(System.in); ArrayList<Integer> values = new ArrayList<>(); ArrayList<String> variables = new ArrayList<>(); while(scan.hasNextLine()) { String line = scan.nextLine(); String[] tokens = line.split(" "); if(!Character.isDigit(tokens[0].charAt(0)) && !line.equals("clear") && !line.equals("var")) { int value = 0; for(int i=0; i<tokens.length; i++) { if(tokens.length==3) { value = Integer.parseInt(tokens[2]); System.out.printf("%5d\n",value); if(map.containsKey(tokens[0])) { values.set(values.indexOf(tokens[0]), value); variables.set(variables.indexOf(tokens[0]), tokens[0]); } else { values.add(value); } break; } else if(tokens[i].charAt(0) == '+') { value = addition(tokens, value); System.out.printf("%5d\n",value); variables.add(tokens[0]); if(map.containsKey(tokens[0])) { values.set(values.indexOf(tokens[0]), value); variables.set(variables.indexOf(tokens[0]), tokens[0]); } else { values.add(value); } break; } else if(i==tokens.length-1 && tokens.length != 3) { System.out.println("No operation"); break; } } map.put(tokens[0], value); } if(Character.isDigit(tokens[0].charAt(0))) { int value = 0; if(tokens.length==1) { System.out.printf("%5s\n", tokens[0]); } else { value = addition(tokens, value); System.out.printf("%5d\n", value); } } if(line.equals("clear")) { clear(map); } if(line.equals("var")) { variableList(variables, values); } } } public static int addition(String[] a, int b) { for(String item : a) { if(Character.isDigit(item.charAt(0))) { int add = Integer.parseInt(item); b = b + add; } } return b; } public static void clear(LinkedHashMap<String,Integer> b) { b.clear(); } public static void variableList(ArrayList<String> a, ArrayList<Integer> b) { for(int i=0; i<a.size(); i++) { System.out.printf("%5s: %d\n", a.get(i), b.get(i)); } } I included the whole code because I'm not sure where the error is arising from.

    Read the article

  • Alphabetically Ordering an array of words

    - by Genesis
    I'm studying C on my own in preparation for my upcoming semester of school and was wondering what I was doing wrong with my code so far. If Things look weird it is because this is part of a much bigger grab bag of sorting functions I'm creating to get a sense of how to sort numbers,letters,arrays,and the like! I'm basically having some troubles with the manipulation of strings in C currently. Also, I'm quite limited in my knowledge of C at the moment! My main Consists of this: #include <stdio.h> #include <stdio.h> #include <stdlib.h> int numbers[10]; int size; int main(void){ setvbuf(stdout,NULL,_IONBF,0); //This is magical code that allows me to input. int wordNumber; int lengthOfWord = 50; printf("How many words do you want to enter: "); scanf("%i", &wordNumber); printf("%i\n",wordNumber); char words[wordNumber][lengthOfWord]; printf("Enter %i words:",wordNumber); int i; for(i=0;i<wordNumber+1;i++){ //+1 is because my words[0] is blank. fgets(&words[i], 50, stdin); } for(i=1;i<wordNumber+1;i++){ // Same as the above comment! printf("%s", words[i]); //prints my words out! } alphabetize(words,wordNumber); //I want to sort these arrays with this function. } My sorting "method" I am trying to construct is below! This function is seriously flawed, but I'd thought I'd keep it all to show you where my mind was headed when writing this. void alphabetize(char a[][],int size){ // This wont fly. size = size+1; int wordNumber; int lengthOfWord; char sortedWords[wordNumber][lengthOfWord]; //In effort for the for loop int i; int j; for(i=1;i<size;i++){ //My effort to copy over this array for manipulation for(j=1;j<size;j++){ sortedWords[i][j] = a[i][j]; } } //This should be kinda what I want when ordering words alphabetically, right? for(i=1;i<size;i++){ for(j=2;j<size;j++){ if(strcmp(sortedWords[i],sortedWords[j]) > 0){ char* temp = sortedWords[i]; sortedWords[i] = sortedWords[j]; sortedWords[j] = temp; } } } for(i=1;i<size;i++){ printf("%s, ",sortedWords[i]); } } I guess I also have another question as well... When I use fgets() it's doing this thing where I get a null word for the first spot of the array. I have had other issues recently trying to scanf() char[] in certain ways specifically spacing my input word variables which "magically" gets rid of the first null space before the character. An example of this is using scanf() to write "Hello" and getting " Hello" or " ""Hello"... Appreciate any thoughts on this, I've got all summer to study up so this doesn't need to be answered with haste! Also, thank you stack overflow as a whole for being so helpful in the past. This may be my first post, but I have been a frequent visitor for the past couple of years and it's been one of the best places for helpful advice/tips.

    Read the article

  • Use of select or multithread for almost 80 or more clients?

    - by Tushar Goel
    I am working on one project in which i need to read from 80 or more clients and then write their o/p into a file continuously and then read these new data for another task. My question is what should i use select or multithreading? Also I tried to use multi threading using read/fgets and write/fputs call but as they are blocking calls and one operation can be performed at one time so it is not feasible. Any idea is much appreciated. update 1: I have tried to implement the same using condition variable. I able to achieve this but it is writing and reading one at a time.When another client tried to write then it cannot able to write unless i quit from the 1st thread. I do not understand this. This should work now. What mistake i am doing? Update 2: Thanks all .. I am able to succeeded to get this model implemented using mutex condition variable. updated Code is as below: **header file******* char *mailbox ; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER ; pthread_cond_t writer = PTHREAD_COND_INITIALIZER; int main(int argc,char *argv[]) { pthread_t t1 , t2; pthread_attr_t attr; int fd, sock , *newfd; struct sockaddr_in cliaddr; socklen_t clilen; void *read_file(); void *update_file(); //making a server socket if((fd=make_server(atoi(argv[1])))==-1) oops("Unable to make server",1) //detaching threads pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED); ///opening thread for reading pthread_create(&t2,&attr,read_file,NULL); while(1) { clilen = sizeof(cliaddr); //accepting request sock=accept(fd,(struct sockaddr *)&cliaddr,&clilen); //error comparison against failire of request and INT if(sock==-1 && errno != EINTR) oops("accept",2) else if ( sock ==-1 && errno == EINTR) oops("Pressed INT",3) newfd = (int *)malloc(sizeof(int)); *newfd = sock; //creating thread per request pthread_create(&t1,&attr,update_file,(void *)newfd); } free(newfd); return 0; } void *read_file(void *m) { pthread_mutex_lock(&lock); while(1) { printf("Waiting for lock.\n"); pthread_cond_wait(&writer,&lock); printf("I am reading here.\n"); printf("%s",mailbox); mailbox = NULL ; pthread_cond_signal(&writer); } } void *update_file(int *m) { int sock = *m; int fs ; int nread; char buffer[BUFSIZ] ; if((fs=open("database.txt",O_RDWR))==-1) oops("Unable to open file",4) while(1) { pthread_mutex_lock(&lock); write(1,"Waiting to get writer lock.\n",29); if(mailbox != NULL) pthread_cond_wait(&writer,&lock); lseek(fs,0,SEEK_END); printf("Reading from socket.\n"); nread=read(sock,buffer,BUFSIZ); printf("Writing in file.\n"); write(fs,buffer,nread); mailbox = buffer ; pthread_cond_signal(&writer); pthread_mutex_unlock(&lock); } close(fs); }

    Read the article

  • Generating 2-dimensional vla ends in segmentation fault

    - by Framester
    Hi, further developing the code from yesterday (seg fault caused by malloc and sscanf in a function), I tried with the help of some tutorials I found on the net to generate a 2-dim vla. But I get a segmentation fault at (*data)[i][j]=atof(p);. The program is supposed to read a matrix out of a text file and load it into a 2d array (cols 1-9) and a 1D array (col 10) [Example code] #include<stdio.h> #include<stdlib.h> #include<math.h> #include<string.h> const int LENGTH = 1024; void read_data(float ***data, int **classes, int *nrow,int *ncol, char *filename){ FILE *pfile = NULL; char line[LENGTH]; if(!( pfile=fopen(filename,"r"))){ printf("Error opening %s.", filename); exit(1); } int numlines=0; int numcols=0; char *p; fgets(line,LENGTH,pfile); p = strtok (line," "); while (p != NULL){ p = strtok (NULL, ", "); numcols++; } while(fgets(line,LENGTH,pfile)){ numlines++; } rewind(pfile); int numfeats=numcols-1; *data=(float**) malloc(numlines*sizeof(float*)); *classes=(int *)malloc(numlines*sizeof(int)); if(*classes == NULL){ printf("\nOut of memory."); exit(1); } int i=0; while(fgets(line,LENGTH,pfile)){ p = strtok (line," "); for(int j=0;j<numfeats;j++) { (data)[i]=malloc(numfeats*sizeof(float)); printf("%i ",i); (*data)[i][j]=atof(p); p = strtok (NULL, ", "); } (*classes)[i]=atoi(p); i++; } fclose(pfile); *nrow=numlines; *ncol=numfeats; } int main() { char *filename="somedatafile.txt"; float **data2; int *classes2; int r,c; read_data(&data2,&classes2, &r, &c,filename) ; for(int i=0;i<r;i++){ printf("\n"); for(int j=0;j<c;j++){ printf("%f",data2[i][j]); } } return 1; } [Content of somedatafile.txt] 50 21 77 0 28 0 27 48 22 2 55 0 92 0 0 26 36 92 56 4 53 0 82 0 52 -5 29 30 2 1 37 0 76 0 28 18 40 48 8 1 37 0 79 0 34 -26 43 46 2 1 85 0 88 -4 6 1 3 83 80 5 56 0 81 0 -4 11 25 86 62 4 55 -1 95 -3 54 -4 40 41 2 1 53 8 77 0 28 0 23 48 24 4 37 0 101 -7 28 0 64 73 8 1 ...

    Read the article

  • Play and record streaming audio

    - by Igor
    I'm working on an iPhone app that should be able to play and record audio streaming data simultaneously. Is it actually possible? I'm trying to mix SpeakHere and AudioRecorder samples and getting an empty file with no audio data... Here is my .m code: import "AzRadioViewController.h" @implementation azRadioViewController static const CFOptionFlags kNetworkEvents = kCFStreamEventOpenCompleted | kCFStreamEventHasBytesAvailable | kCFStreamEventEndEncountered | kCFStreamEventErrorOccurred; void MyAudioQueueOutputCallback( void* inClientData, AudioQueueRef inAQ, AudioQueueBufferRef inBuffer, const AudioTimeStamp inStartTime, UInt32 inNumberPacketDescriptions, const AudioStreamPacketDescription inPacketDesc ) { NSLog(@"start MyAudioQueueOutputCallback"); MyData* myData = (MyData*)inClientData; NSLog(@"--- %i", inNumberPacketDescriptions); if(inNumberPacketDescriptions == 0 && myData-dataFormat.mBytesPerPacket != 0) { inNumberPacketDescriptions = inBuffer-mAudioDataByteSize / myData-dataFormat.mBytesPerPacket; } OSStatus status = AudioFileWritePackets(myData-audioFile, FALSE, inBuffer-mAudioDataByteSize, inPacketDesc, myData-currentPacket, &inNumberPacketDescriptions, inBuffer-mAudioData); if(status == 0) { myData-currentPacket += inNumberPacketDescriptions; } NSLog(@"status:%i curpac:%i pcdesct: %i", status, myData-currentPacket, inNumberPacketDescriptions); unsigned int bufIndex = MyFindQueueBuffer(myData, inBuffer); pthread_mutex_lock(&myData-mutex); myData-inuse[bufIndex] = false; pthread_cond_signal(&myData-cond); pthread_mutex_unlock(&myData-mutex); } OSStatus StartQueueIfNeeded(MyData* myData) { NSLog(@"start StartQueueIfNeeded"); OSStatus err = noErr; if (!myData-started) { err = AudioQueueStart(myData-queue, NULL); if (err) { PRINTERROR("AudioQueueStart"); myData-failed = true; return err; } myData-started = true; printf("started\n"); } return err; } OSStatus MyEnqueueBuffer(MyData* myData) { NSLog(@"start MyEnqueueBuffer"); OSStatus err = noErr; myData-inuse[myData-fillBufferIndex] = true; AudioQueueBufferRef fillBuf = myData-audioQueueBuffer[myData-fillBufferIndex]; fillBuf-mAudioDataByteSize = myData-bytesFilled; err = AudioQueueEnqueueBuffer(myData-queue, fillBuf, myData-packetsFilled, myData-packetDescs); if (err) { PRINTERROR("AudioQueueEnqueueBuffer"); myData-failed = true; return err; } StartQueueIfNeeded(myData); return err; } void WaitForFreeBuffer(MyData* myData) { NSLog(@"start WaitForFreeBuffer"); if (++myData-fillBufferIndex = kNumAQBufs) myData-fillBufferIndex = 0; myData-bytesFilled = 0; myData-packetsFilled = 0; printf("-lock\n"); pthread_mutex_lock(&myData-mutex); while (myData-inuse[myData-fillBufferIndex]) { printf("... WAITING ...\n"); pthread_cond_wait(&myData-cond, &myData-mutex); } pthread_mutex_unlock(&myData-mutex); printf("<-unlock\n"); } int MyFindQueueBuffer(MyData* myData, AudioQueueBufferRef inBuffer) { NSLog(@"start MyFindQueueBuffer"); for (unsigned int i = 0; i < kNumAQBufs; ++i) { if (inBuffer == myData-audioQueueBuffer[i]) return i; } return -1; } void MyAudioQueueIsRunningCallback( void* inClientData, AudioQueueRef inAQ, AudioQueuePropertyID inID) { NSLog(@"start MyAudioQueueIsRunningCallback"); MyData* myData = (MyData*)inClientData; UInt32 running; UInt32 size; OSStatus err = AudioQueueGetProperty(inAQ, kAudioQueueProperty_IsRunning, &running, &size); if (err) { PRINTERROR("get kAudioQueueProperty_IsRunning"); return; } if (!running) { pthread_mutex_lock(&myData-mutex); pthread_cond_signal(&myData-done); pthread_mutex_unlock(&myData-mutex); } } void MyPropertyListenerProc( void * inClientData, AudioFileStreamID inAudioFileStream, AudioFileStreamPropertyID inPropertyID, UInt32 * ioFlags) { NSLog(@"start MyPropertyListenerProc"); MyData* myData = (MyData*)inClientData; OSStatus err = noErr; printf("found property '%c%c%c%c'\n", (inPropertyID24)&255, (inPropertyID16)&255, (inPropertyID8)&255, inPropertyID&255); switch (inPropertyID) { case kAudioFileStreamProperty_ReadyToProducePackets : { AudioStreamBasicDescription asbd; UInt32 asbdSize = sizeof(asbd); err = AudioFileStreamGetProperty(inAudioFileStream, kAudioFileStreamProperty_DataFormat, &asbdSize, &asbd); if (err) { PRINTERROR("get kAudioFileStreamProperty_DataFormat"); myData-failed = true; break; } err = AudioQueueNewOutput(&asbd, MyAudioQueueOutputCallback, myData, NULL, NULL, 0, &myData-queue); if (err) { PRINTERROR("AudioQueueNewOutput"); myData-failed = true; break; } for (unsigned int i = 0; i < kNumAQBufs; ++i) { err = AudioQueueAllocateBuffer(myData-queue, kAQBufSize, &myData-audioQueueBuffer[i]); if (err) { PRINTERROR("AudioQueueAllocateBuffer"); myData-failed = true; break; } } UInt32 cookieSize; Boolean writable; err = AudioFileStreamGetPropertyInfo(inAudioFileStream, kAudioFileStreamProperty_MagicCookieData, &cookieSize, &writable); if (err) { PRINTERROR("info kAudioFileStreamProperty_MagicCookieData"); break; } printf("cookieSize %d\n", cookieSize); void* cookieData = calloc(1, cookieSize); err = AudioFileStreamGetProperty(inAudioFileStream, kAudioFileStreamProperty_MagicCookieData, &cookieSize, cookieData); if (err) { PRINTERROR("get kAudioFileStreamProperty_MagicCookieData"); free(cookieData); break; } err = AudioQueueSetProperty(myData-queue, kAudioQueueProperty_MagicCookie, cookieData, cookieSize); free(cookieData); if (err) { PRINTERROR("set kAudioQueueProperty_MagicCookie"); break; } err = AudioQueueAddPropertyListener(myData-queue, kAudioQueueProperty_IsRunning, MyAudioQueueIsRunningCallback, myData); if (err) { PRINTERROR("AudioQueueAddPropertyListener"); myData-failed = true; break; } break; } } } static void ReadStreamClientCallBack(CFReadStreamRef stream, CFStreamEventType type, void *clientCallBackInfo) { NSLog(@"start ReadStreamClientCallBack"); if(type == kCFStreamEventHasBytesAvailable) { UInt8 buffer[2048]; CFIndex bytesRead = CFReadStreamRead(stream, buffer, sizeof(buffer)); if (bytesRead < 0) { } else if (bytesRead) { OSStatus err = AudioFileStreamParseBytes(globalMyData-audioFileStream, bytesRead, buffer, 0); if (err) { PRINTERROR("AudioFileStreamParseBytes"); } } } } void MyPacketsProc(void * inClientData, UInt32 inNumberBytes, UInt32 inNumberPackets, const void * inInputData, AudioStreamPacketDescription inPacketDescriptions) { NSLog(@"start MyPacketsProc"); MyData myData = (MyData*)inClientData; printf("got data. bytes: %d packets: %d\n", inNumberBytes, inNumberPackets); for (int i = 0; i < inNumberPackets; ++i) { SInt64 packetOffset = inPacketDescriptions[i].mStartOffset; SInt64 packetSize = inPacketDescriptions[i].mDataByteSize; size_t bufSpaceRemaining = kAQBufSize - myData-bytesFilled; if (bufSpaceRemaining < packetSize) { MyEnqueueBuffer(myData); WaitForFreeBuffer(myData); } AudioQueueBufferRef fillBuf = myData-audioQueueBuffer[myData-fillBufferIndex]; memcpy((char*)fillBuf-mAudioData + myData-bytesFilled, (const char*)inInputData + packetOffset, packetSize); myData-packetDescs[myData-packetsFilled] = inPacketDescriptions[i]; myData-packetDescs[myData-packetsFilled].mStartOffset = myData-bytesFilled; myData-bytesFilled += packetSize; myData-packetsFilled += 1; size_t packetsDescsRemaining = kAQMaxPacketDescs - myData-packetsFilled; if (packetsDescsRemaining == 0) { MyEnqueueBuffer(myData); WaitForFreeBuffer(myData); } } } (IBAction)buttonPlayPressedid)sender { label.text = @"Buffering"; [self connectionStart]; } (IBAction)buttonSavePressedid)sender { NSLog(@"save"); AudioFileClose(myData.audioFile); AudioQueueDispose(myData.queue, TRUE); } bool getFilename(char* buffer,int maxBufferLength) { NSArray paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString docDir = [paths objectAtIndex:0]; NSString* file = [docDir stringByAppendingString:@"/rec.caf"]; return [file getCString:buffer maxLength:maxBufferLength encoding:NSUTF8StringEncoding]; } -(void)connectionStart { @try { MyData* myData = (MyData*)calloc(1, sizeof(MyData)); globalMyData = myData; pthread_mutex_init(&myData-mutex, NULL); pthread_cond_init(&myData-cond, NULL); pthread_cond_init(&myData-done, NULL); NSLog(@"Start"); myData-dataFormat.mSampleRate = 16000.0f; myData-dataFormat.mFormatID = kAudioFormatLinearPCM; myData-dataFormat.mFramesPerPacket = 1; myData-dataFormat.mChannelsPerFrame = 1; myData-dataFormat.mBytesPerFrame = 2; myData-dataFormat.mBytesPerPacket = 2; myData-dataFormat.mBitsPerChannel = 16; myData-dataFormat.mReserved = 0; myData-dataFormat.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked; int i, bufferByteSize; UInt32 size; AudioQueueNewInput( &myData-dataFormat, MyAudioQueueOutputCallback, &myData, NULL /* run loop /, kCFRunLoopCommonModes / run loop mode /, 0 / flags */, &myData-queue); size = sizeof(&myData-dataFormat); AudioQueueGetProperty(&myData-queue, kAudioQueueProperty_StreamDescription, &myData-dataFormat, &size); CFURLRef fileURL; char path[256]; memset(path,0,sizeof(path)); getFilename(path,256); fileURL = CFURLCreateFromFileSystemRepresentation(NULL, (UInt8*)path, strlen(path), FALSE); AudioFileCreateWithURL(fileURL, kAudioFileCAFType, &myData-dataFormat, kAudioFileFlags_EraseFile, &myData-audioFile); OSStatus err = AudioFileStreamOpen(myData, MyPropertyListenerProc, MyPacketsProc, kAudioFileMP3Type, &myData-audioFileStream); if (err) { PRINTERROR("AudioFileStreamOpen"); return 1; } CFStreamClientContext ctxt = {0, self, NULL, NULL, NULL}; CFStringRef bodyData = CFSTR(""); // Usually used for POST data CFStringRef headerFieldName = CFSTR("X-My-Favorite-Field"); CFStringRef headerFieldValue = CFSTR("Dreams"); CFStringRef url = CFSTR(RADIO_LOCATION); CFURLRef myURL = CFURLCreateWithString(kCFAllocatorDefault, url, NULL); CFStringRef requestMethod = CFSTR("GET"); CFHTTPMessageRef myRequest = CFHTTPMessageCreateRequest(kCFAllocatorDefault, requestMethod, myURL, kCFHTTPVersion1_1); CFHTTPMessageSetBody(myRequest, bodyData); CFHTTPMessageSetHeaderFieldValue(myRequest, headerFieldName, headerFieldValue); CFReadStreamRef stream = CFReadStreamCreateForHTTPRequest(kCFAllocatorDefault, myRequest); if (!stream) { NSLog(@"Creating the stream failed"); return; } if (!CFReadStreamSetClient(stream, kNetworkEvents, ReadStreamClientCallBack, &ctxt)) { CFRelease(stream); NSLog(@"Setting the stream's client failed."); return; } CFReadStreamScheduleWithRunLoop(stream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes); if (!CFReadStreamOpen(stream)) { CFReadStreamSetClient(stream, 0, NULL, NULL); CFReadStreamUnscheduleFromRunLoop(stream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes); CFRelease(stream); NSLog(@"Opening the stream failed."); return; } } @catch (NSException *exception) { NSLog(@"main: Caught %@: %@", [exception name], [exception reason]); } } (void)viewDidLoad { [[UIApplication sharedApplication] setIdleTimerDisabled:YES]; [super viewDidLoad]; } (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; } (void)viewDidUnload { } (void)dealloc { [super dealloc]; } @end

    Read the article

  • Mutual piping on linux

    - by user21919
    I would like the output of A to be input for B and at the same time the output of B to be the input for A, is that possible? I tried the naïve thing: creating named pipes for A (pipeA) and B (pipeB) and then: pipeB | A | pipeA & pipeA | B | pipeB & But that does not work (pipeB is empty and switching the order would not help either). Any help would be appreciated. Example: Command A could be compiled form of this C program: #include <stdio.h> int main() { printf("0\n"); int x = 0; while (scanf("%d", &x) != EOF) { printf("%d\n", x + 1); } return 0; } Command B could be compiled form of this C program: #include <stdio.h> int main() { int x = 0; while (scanf("%d", &x) != EOF) { printf("%d\n", x + x); } return 0; }

    Read the article

  • Pointer arithmetic and arrays: what's really legal?

    - by bitcruncher
    Consider the following statements: int *pFarr, *pVarr; int farr[3] = {11,22,33}; int varr[3] = {7,8,9}; pFarr = &(farr[0]); pVarr = varr; At this stage, both pointers are pointing at the start of each respective array address. For *pFarr, we are presently looking at 11 and for *pVarr, 7. Equally, if I request the contents of each array through *farr and *varr, i also get 11 and 7. So far so good. Now, let's try pFarr++ and pVarr++. Great. We're now looking at 22 and 8, as expected. But now... Trying to move up farr++ and varr++ ... and we get "wrong type of argument to increment". Now, I recognize the difference between an array pointer and a regular pointer, but since their behaviour is similar, why this limitation? This is further confusing to me when I also consider that in the same program I can call the following function in an ostensibly correct way and in another incorrect way, and I get the same behaviour, though in contrast to what happened in the code posted above!? working_on_pointers ( pFarr, farr ); // calling with expected parameters working_on_pointers ( farr, pFarr ); // calling with inverted parameters . void working_on_pointers ( int *pExpect, int aExpect[] ) { printf("%i", *pExpect); // displays the contents of pExpect ok printf("%i", *aExpect); // displays the contents of aExpect ok pExpect++; // no warnings or errors aExpect++; // no warnings or errors printf("%i", *pExpect); // displays the next element or an overflow element (with no errors) printf("%i", *aExpect); // displays the next element or an overflow element (with no errors) } Could someone help me to understand why array pointers and pointers behave in similar ways in some contexts, but different in others? So many thanks. EDIT: Noobs like myself could further benefit from this resource: http://www.panix.com/~elflord/cpp/gotchas/index.shtml

    Read the article

  • problem with awk script

    - by Samantha
    Hello, when I call my awk script, I keep getting an error : sam@sam-laptop:~/shell/td4$ awk -f agenda.awk -- -n Robert agenda.txt awk: agenda.awk:6: printf "Hello" awk: agenda.awk:6: ^ syntax error the script contains this : #!/usr/bin/awk BEGIN { } printf "Hello" END { } Thank you

    Read the article

  • Binary Search Tree in C

    - by heapzero
    Hi, I'm a Python guy. Learning C language and I've been trying to implement Binary Search Tree in C. I wrote down the code, and I've been trying from few hours but, not able to get the output as expected. Please help! Please correct me. #include<stdlib.h> #include<stdio.h> typedef int ElementType; typedef struct TreeNode { ElementType element; struct TreeNode *left, *right; } TreeNode; TreeNode *createTree(){ //Create the root of tree TreeNode *tempNode; tempNode = malloc(sizeof(TreeNode)); tempNode->element = 0; tempNode->left = NULL; tempNode->right = NULL; return tempNode; } TreeNode *createNode(ElementType X){ //Create a new leaf node and return the pointer TreeNode *tempNode; tempNode = malloc(sizeof(TreeNode)); tempNode->element = X; tempNode->left = NULL; tempNode->right = NULL; return tempNode; } TreeNode *insertElement(TreeNode *node, ElementType X){ //insert element to Tree if(node==NULL){ return createNode(X); } else{ if(X < node->element){ node->left = insertElement(node->left, X); } else if(X > node->element){ node->right = insertElement(node->right, X); } else if(X == node->element){ printf("Oops! the element is already present in the tree."); } } } TreeNode *displayTree(TreeNode *node){ //display the full tree if(node==NULL){ return; } displayTree(node->left); printf("| %d ", node->element); displayTree(node->right); } main(){ //pointer to root of tree #2 TreeNode *TreePtr; TreeNode *TreeRoot; TreeNode *TreeChild; //Create the root of tree TreePtr = createTree(); TreeRoot = TreePtr; TreeRoot->element = 32; printf("%d\n",TreeRoot->element); insertElement(TreeRoot, 8); TreeChild = TreeRoot->left; printf("%d\n",TreeChild->element); insertElement(TreeRoot, 2); insertElement(TreeRoot, 7); insertElement(TreeRoot, 42); insertElement(TreeRoot, 28); insertElement(TreeRoot, 1); insertElement(TreeRoot, 4); insertElement(TreeRoot, 5); // the output is not as expected :( displayTree(TreeRoot); }

    Read the article

< Previous Page | 16 17 18 19 20 21 22 23 24 25 26 27  | Next Page >