#include <string.h>
#include <stdio.h>
#include "..\..\Lib\g4500.h"			
#include "..\..\Lib\microSD.h"


char write_buffer[129],readback_buffer[129]; 
void main(void)
{ 
    int quit=0; 
    int out_fd;
    int testcnt=0;
    int iLen,iRet;
    long st;
  
    char file_name[15];
    
    InitLib();
    if (!pc_init())
		Print("pc_ertfs_init failed");
    else
    {
      	st=GetTimeTicks();   
    	while(!quit)
    	{
    		if(Kbhit() && Getch()==27) break;  //press ESC to quit.
    		if(GetTimeTicks()-st>1000)  //execute the writing every 1000 ms.
    		{ 
        		st=GetTimeTicks();
       		    
       		    strcpy(file_name,"test.txt");
       		    out_fd=pc_open(file_name,(word)(PO_WRONLY|PO_CREAT|PO_APPEND),
      		                   (word)(PS_IWRITE|PS_IREAD));
        		if (out_fd< 0)
        		{
        			Print("pc_open error\n\r");
        			break;
        		}
        		else 
        		{
        			iLen=sprintf(write_buffer,"Line:%09d\r\n",testcnt++);
        			Puts(write_buffer);
        			iRet=pc_write(out_fd,write_buffer,iLen);
        			if (iRet != iLen)
        			{
        				Print("pc_write error(iLen=%d,iRet=%d)\r\n",iLen,iRet);
        				quit=1;
        			}
        			else
        			{
        				/* check of write */
						pc_seek(out_fd, (-1*iLen), PSEEK_CUR);
						iRet=pc_read(out_fd, readback_buffer, iLen);
        				readback_buffer[iLen]='\0';
        				if (strncmp(write_buffer,readback_buffer,iLen))
        				{
        					Print("ReadBack Error:%s",readback_buffer);
        					quit=1;
        				}
        			}	
        			pc_close(out_fd);
        		}
            }
    	}
    }
}	
