Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

C file I/O

  1. Jul 3, 2009 #1

    I am working on some software to control oscilloscopes and function generators in a physics lab. The situation I am faced with at the moment is to be able to translate integers into a form which can be loaded into a device.

    So basically I have a file which looks like this:


    where (n) is actually something really crazy (possibly including whitespace). (The actual file starts like "^A**NEXT**^B**NEXT**...).

    I am trying to write a program in C which will let me input any int n with 1<=n and n<=16383 and which will go through the file to find (n) and output it.

    So basically it is a problem of dealing with an ugly mess of characters. Do you all have any suggestions or know of any built in functions which might be useful for this?

    Also, when using file input in C, I tend to run into the problem where I can only move forward in the file. Is there an easy way to move backwards as well? What about a way of searching for the next "**NEXT**"? Anyway, sorry about the long question. Any advice at all would be nice!

  2. jcsd
  3. Jul 5, 2009 #2
    Last edited by a moderator: Apr 24, 2017
  4. Jul 5, 2009 #3


    User Avatar
    Homework Helper

    If this is being implemnted on PC, chances are that your file will easily fit into memory, so you might as well read the entire file in a sufficiently large allocated block of memory.

    If the CPU is intel based, there's a fast search for character option, memchr().

    Code (Text):

    BYTE  abNext = "**NEXT**"
    PBYTE pMem;
    PBYTE pCurrent;
    PBYTE pSearch;
    int   iCount;
    int   iSkip;

        pMem = malloc(0x100000)   // allocate 16mb ram

    //  read file, store # of bytes in iCount

        pCurrent = pMem;

            if( (iCount <= 0) ||
                ((PBYTE)0 == pSearch = (PBYTE) memchr(pCurrent, '*', iCount))){
                // ... end of file
            if(0 == memcmp(pCurrent, abNext, sizeof(abNext){
                // ... match found
                iSkip += (pSearch-pCurrent) + sizeof(abNext) + ...;
                pCurrent += iSkip;
                iCount -= iSkip;
  5. Jul 7, 2009 #4


    User Avatar
    Homework Helper

    Allocated size was wrong, that was 1mb

    Code (Text):

        pMem0 = malloc(  0x100000)   // allocate   1mb ram
        pMem1 = malloc( 0x1000000)   // allocate  16mb ram
        pMem2 = malloc(0x10000000)   // allocate 256mb ram
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook