Search Results

Search found 222 results on 9 pages for 'fwrite'.

Page 3/9 | < Previous Page | 1 2 3 4 5 6 7 8 9  | Next Page >

  • how to find the directory already is there or not in php

    - by zahir hussain
    hi i want know find the directory is already there or not... if not i would like to create the directory... my coding is below... $da = getdate(); $dat = $da["year"]."-".$da["mon"]."-".$da["mday"]; $m = md5($url)."xml"; if(is_dir($dat)) { chdir($dat); $fh = fopen($m, 'w'); fwrite($fh, $xml); fclose($fh); echo "yes"; } else { mkdir($dat,0777,true); chdir($dat); $fh = fopen($m, 'w'); fwrite($fh, $xml); fclose($fh); echo "not"; } thanks and advance

    Read the article

  • File IO, Handling CRLF

    - by aCuria
    Hi, i am writing a program that takes a file and splits it up into multiple small files of a user specified size, then join the multiple small files back again. 1) the code must work for c, c++ 2) i am compiling with multiple compilers. I am reading and writing to the files by using the stl functions fread() and fwrite() The problem I am having pertains to CRLF. If the file I am reading from contains CRLF, then I want to retain it when i split and join the files back together. If the file contains LF, then i want to retain LF. Unfortunately, fread() seems to store CRLF as \n (I think), and whatever is written by fwrite() is compiler-dependent. How do i approach this problem? Thanks.

    Read the article

  • Sending JSON(jQuery) to PHP and decoding it

    - by dscher
    I can't for the life of me figure out what I'm doing wrong. It seems like it should be simple because I can't find anyone else with this issue but I can't figure out to send basic data via javascript(jQuery) to PHP and decode it. For the sake of simplicity, this is what I have: JAVASCRIPT var json_data = { "name" : "john doe" }; $.ajax({ type: "POST", url: "../bin/process.php", dataType: "json", data: json_data }); and my PHP FILE $arr = json_decode("json_data", true); $fp = fopen('data.txt', "w"); fwrite($fp, $arr['name']); fclose($fp); The file I'm writing ends up with nothing in it. If I do an: fwrite($fp, 'test'); I get a file with the word test in it but no matter what I do I don't get the json data I sent. Can someone please share a thorough example of A to Z. Thanks for any help.

    Read the article

  • Sending JSON(jQuery) to PHP and decoding it

    - by dscher
    I can't for the life of me figure out what I'm doing wrong. It seems like it should be simple because I can't find anyone else with this issue but I can't figure out to send basic data via javascript(jQuery) to PHP and decode it. For the sake of simplicity, this is what I have: JAVASCRIPT var json_data = { "name" : "john doe" }; $.ajax({ type: "POST", url: "../bin/process.php", dataType: "json", data: json_data }); and my PHP FILE $arr = json_decode("json_data", true); $fp = fopen('data.txt', "w"); fwrite($fp, $arr['name']); fclose($fp); The file I'm writing ends up with nothing in it. If I do an: fwrite($fp, 'test'); I get a file with the word test in it but no matter what I do I don't get the json data I sent. Can someone please share a thorough example of A to Z. Thanks for any help.

    Read the article

  • PHP write file... need help

    - by Jordan Pagaduan
    <?php $title = $_POST['title']; $filename = $title , ".php"; $fh = fopen($filename, 'w') or die ("can't open file"); $stringData = $title; fwrite($fh, $stringData); $stringData = $blog; fwrite($fh, $stringData); fclose($fh); ?> This is only a sample. What is the correct code for that?

    Read the article

  • write image file larger than 4096

    - by ntan
    Hi, *************EDIT********** i am using ODBC and found that can not read more than 4096 for a field Any suggestions *************EDIT************ i am reading an image from db $image=$row["image-contents"]; Now try to write the file to disk $image_name="test.jpg"; $file = fopen( "images/".$image_name, "w" ); fwrite( $file, $image); fclose( $file ); The problem is that the file created is only 4096 bytes and the image file is corrupt because $image is larger than 4096. I now that fwrite use blocks for write but i dont know how do it. Help plz!

    Read the article

  • I was stuck in implementing Simple Ftp with Winsock [migrated]

    - by user67449
    I want to implement a SimpleFtp with Winsock. But I was stuck in the maybe the file stream reading and writing. This is the Server. #include <WinSock2.h> #include <memory.h> #include <stdio.h> #include <iostream> using namespace std; #pragma comment(lib, "ws2_32.lib") #define MAX_FILE_NAME 100 #define DATA_PACK_SIZE 80*1000 // ??DataPack?????80KB #define SOCKKET_BUFFER_SIZE 80*1000 // socket??? #define FILE_BUFFER_SIZE DATA_PACK_SIZE-MAX_FILE_NAME-4*sizeof(int)-sizeof(u_long) //?????,??,??????content????? #define CONTENT_SIZE FILE_BUFFER_SIZE // DataPack?????content??? // Define a structure to hold the content of a file typedef struct FilePack{ char fName[MAX_FILE_NAME]; // File's name int fLen; // File's length int packNum; // Number of the DataPack int packLen; // DataPack's length int packCount; int contenLen; // the content length the DataPack actually holds u_long index; // ?????????? char content[CONTENT_SIZE]; // DataPack?????? }DataPack, *pDataPack; void WinsockInitial(){ WSADATA wsaData; WORD wVersionRequested; int err; wVersionRequested=MAKEWORD(2,2); err=WSAStartup(wVersionRequested, &wsaData); if(err!=0){ cout<<"Error at WSAStartup()."<<endl; exit(0); } if( LOBYTE(wsaData.wVersion)!=2 || HIBYTE(wsaData.wVersion)!=2 ){ cout<<"Error at version of Winsock. "<<endl; WSACleanup(); exit(0); } } void SockBind(SOCKET sock, int port, sockaddr_in &addrsock){ addrsock.sin_family=AF_INET; addrsock.sin_port=htons(port); addrsock.sin_addr.S_un.S_addr=htonl(INADDR_ANY); if( bind(sock, (sockaddr*)&addrsock, sizeof(addrsock)) == SOCKET_ERROR ){ cout<<"Error at bind(). Error: "<<GetLastError()<<endl; closesocket(sock); WSACleanup(); exit(0); } } void SockListen(SOCKET sock, int bak){ int err=listen(sock, bak); if(err==SOCKET_ERROR){ cout<<"Error at listen()."<<WSAGetLastError()<<endl; closesocket(sock); WSACleanup(); exit(0); } } int SockSend(DataPack &dataPack, SOCKET sock, char *sockBuf){ int bytesLeft=0, bytesSend=0; int idx=0; bytesLeft=sizeof(dataPack); // ?DataPack?????sockBuf??? memcpy(sockBuf, &dataPack, sizeof(dataPack)); while(bytesLeft>0){ bytesSend=send(sock, &sockBuf[idx], bytesLeft, 0); if(bytesSend==SOCKET_ERROR){ cout<<"Error at send()."<<endl; return 1; } bytesLeft-=bytesSend; idx+=bytesSend; } return 0; } int GetFileLen(FILE *fp){ // ?????? if(fp==NULL){ cout<<"Invalid argument. Error at GetFileLen()."<<endl; exit(0); } fseek(fp, 0, SEEK_END); int tempFileLen=ftell(fp); fseek(fp, 0, SEEK_SET); return tempFileLen; } int main(){ int err; sockaddr_in addrServ; int port=8000; // Initialize Winsock WinsockInitial(); // Create a socket SOCKET sockListen=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if(sockListen==INVALID_SOCKET){ cout<<"Error at socket()."<<endl; WSACleanup(); return 1; } // Bind the socket. SockBind(sockListen, port, addrServ); // Listen for incoming connection requests cout<<"Waiting for incoming connection requests..."<<endl; SockListen(sockListen, 5); // Accept the connection request. sockaddr_in addrClient; int len=sizeof(addrClient); SOCKET sockConn=accept(sockListen, (sockaddr*)&addrClient, &len); if(sockConn!=INVALID_SOCKET){ cout<<"Connected to client successfully."<<endl; } // Set the buffer size of socket char sockBuf[SOCKKET_BUFFER_SIZE]; int nBuf=SOCKKET_BUFFER_SIZE; int nBufLen=sizeof(nBuf); err=setsockopt(sockConn, SOL_SOCKET, SO_SNDBUF, (char*)&nBuf, nBufLen); if(err!=0){ cout<<"Error at setsockopt(). Failed to set buffer size for socket."<<endl; exit(0); } //??????????? err = getsockopt(sockConn, SOL_SOCKET, SO_SNDBUF, (char*)&nBuf, &nBufLen); if( SOCKKET_BUFFER_SIZE != nBuf){ cout<<"Error at setsockopt(). ?socket????????"<<endl; closesocket(sockListen); closesocket(sockConn); WSACleanup(); exit(0); } //------------------------------------------------------------------------// DataPack dataPackSend; memset(&dataPackSend, 0, sizeof(dataPackSend)); int bytesRead; int bytesLeft; int bytesSend; int packCount; // Counts how many DataPack needed FILE *frp; // Used to read if(strcpy_s(dataPackSend.fName, "music.mp3")!=0){ cout<<"Error at strcpy_s()."<<endl; return 1; } // Open the file in read+binary mode err=fopen_s(&frp, dataPackSend.fName, "rb"); if(err!=0){ cout<<"Error at fopen_s()."<<endl; return 1; } char fileBuf[FILE_BUFFER_SIZE]; // Set the buffer size of File if(setvbuf(frp, fileBuf, _IONBF, FILE_BUFFER_SIZE)!=0){ cout<<"Error at setvbuf().Failed to set buffer size for file."<<endl; closesocket(sockListen); closesocket(sockConn); WSACleanup(); exit(0); } // Get file's length int fileLen=GetFileLen(frp); cout<<"File ???:"<<fileLen<<" bytes."<<endl; // Calculate how many DataPacks needed packCount=ceil( (double)fileLen/CONTENT_SIZE ); cout<<"File Length: "<<fileLen<<" "<<"Content Size: "<<CONTENT_SIZE<<endl; cout<<"???"<<packCount<<" ?DataPack"<<endl; int i=0; for(i=0; i<packCount; i++){ //?????dataPackSend????? memset(&dataPackSend, 0, sizeof(dataPackSend)); // Fill the dataPackSend if(strcpy_s(dataPackSend.fName, "abc.txt")!=0){ cout<<"Error at strcpy_s()."<<endl; return 1; } dataPackSend.packLen=DATA_PACK_SIZE; dataPackSend.fLen=fileLen; dataPackSend.packCount=packCount; if( packCount==1 ){ //??DataPack??? bytesRead=fread(fileBuf, 1, dataPackSend.fLen, frp); dataPackSend.contenLen=dataPackSend.fLen; memcpy(dataPackSend.content, fileBuf, bytesRead); dataPackSend.packNum=0; //???????DataPack // ?????dataPackSend?Client? if( SockSend(dataPackSend, sockConn, sockBuf)==0 ){ cout<<"??? "<<dataPackSend.packNum<<" ?DataPack"<<endl; } }else if( packCount>1 && i<(packCount-1) ){ // ???(???????) bytesRead=fread(fileBuf, 1, CONTENT_SIZE, frp); dataPackSend.contenLen=CONTENT_SIZE; memcpy(dataPackSend.content, fileBuf, bytesRead); dataPackSend.packNum=i; //?dataPackSend??????Client? if( SockSend(dataPackSend, sockConn, sockBuf)==0 ){ cout<<"??? "<<dataPackSend.packNum<<" ?DataPack."<<endl; } }else{ // ????? bytesRead=fread(fileBuf, 1, (dataPackSend.fLen-i*CONTENT_SIZE), frp); dataPackSend.contenLen=dataPackSend.fLen-i*CONTENT_SIZE; memcpy(dataPackSend.content, fileBuf, bytesRead); dataPackSend.packNum=i; //?dataPackSend???Client? if( SockSend(dataPackSend, sockConn, sockBuf)==0 ){ cout<<"??? "<<dataPackSend.packNum<<" ?DataPack."<<endl; } } } fclose(frp); closesocket(sockListen); closesocket(sockConn); WSACleanup(); return 0; } And this is Client. #include <WinSock2.h> #include <memory.h> #include <stdio.h> #include <iostream> using namespace std; #pragma comment(lib, "ws2_32.lib") #define MAX_FILE_NAME 100 #define DATA_PACK_SIZE 80*1000 // ??DataPack?????80KB #define SOCKKET_BUFFER_SIZE 80*1000 // socket??? #define FILE_BUFFER_SIZE DATA_PACK_SIZE-MAX_FILE_NAME-4*sizeof(int)-sizeof(u_long) //?????,??,??????content????? #define CONTENT_SIZE FILE_BUFFER_SIZE // DataPack?????content??? // Define a structure to hold the content of a file typedef struct FilePack{ char fName[MAX_FILE_NAME]; // File's name int fLen; // File's length int packNum; // Number of the DataPack int packLen; // DataPack's length int packCount; //DataPack??? int contenLen; // the content length the DataPack actually holds u_long index; // ?????????? char content[CONTENT_SIZE]; // DataPack?????? }DataPack, *pDataPack; void WinsockInitial(){ WSADATA wsaData; WORD wVersionRequested; int err; wVersionRequested=MAKEWORD(2,2); err=WSAStartup(wVersionRequested, &wsaData); if(err!=0){ cout<<"Error at WSAStartup()."<<endl; exit(0); } if( LOBYTE(wsaData.wVersion)!=2 || HIBYTE(wsaData.wVersion)!=2 ){ cout<<"Error at version of Winsock. "<<endl; WSACleanup(); exit(0); } } int SockRecv(SOCKET sock, char *sockBuf){ int bytesLeft, bytesRecv; int idx=0; bytesLeft=DATA_PACK_SIZE; while(bytesLeft>0){ bytesRecv=recv(sock, &sockBuf[idx], bytesLeft, 0); if(bytesRecv==SOCKET_ERROR){ cout<<"Error at recv()."<<endl; return 1; } bytesLeft-=bytesRecv; idx+=bytesRecv; } return 0; } int main(){ int err; sockaddr_in addrServ; int port=8000; // Initialize Winsock WinsockInitial(); // Create a socket SOCKET sockClient=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if(sockClient==INVALID_SOCKET){ cout<<"Error at socket()."<<endl; WSACleanup(); return 1; } // Set the buffer size of socket char sockBuf[SOCKKET_BUFFER_SIZE]; int nBuf=SOCKKET_BUFFER_SIZE; int nBufLen=sizeof(nBuf); err=setsockopt(sockClient, SOL_SOCKET, SO_RCVBUF, (char*)&nBuf, nBufLen); if(err!=0){ cout<<"Error at setsockopt(). Failed to set buffer size for socket."<<endl; exit(0); } //??????????? err = getsockopt(sockClient, SOL_SOCKET, SO_RCVBUF, (char*)&nBuf, &nBufLen); if( SOCKKET_BUFFER_SIZE != nBuf){ cout<<"Error at getsockopt(). ?socket????????"<<endl; closesocket(sockClient); WSACleanup(); exit(0); } // Connect to the Server addrServ.sin_family=AF_INET; addrServ.sin_port=htons(port); addrServ.sin_addr.S_un.S_addr=inet_addr("127.0.0.1"); err=connect(sockClient, (sockaddr*)&addrServ, sizeof(sockaddr)); if(err==SOCKET_ERROR){ cout<<"Error at connect()."<<GetLastError()<<endl; closesocket(sockClient); WSACleanup(); return 1; }else{ cout<<"Connected to the FTP Server successfully."<<endl; } /* int i=0; int bytesRecv, bytesLeft, bytesWrite; int packCount=0, fLen=0; DataPack dataPackRecv; //?????? SockRecv(sockClient, sockBuf); memcpy(&dataPackRecv, sockBuf, sizeof(dataPackRecv)); cout<<"???? "<<dataPackRecv.packNum<<" ?DataPack."<<endl; cout<<"?DataPack??fName????: "<<dataPackRecv.fName<<endl; //??????? packCount=dataPackRecv.packCount; cout<<"?? "<<packCount<<" ?DataPack."<<endl; fLen=dataPackRecv.fLen; // Create a local file to write into FILE *fwp; err=fopen_s(&fwp, dataPackRecv.fName, "wb"); if(err!=0){ cout<<"Error at creat fopen_s(). Failed to create a local file to write into."<<endl; return 1; } // Set the buffer size of File char fileBuf[FILE_BUFFER_SIZE]; if(setvbuf(fwp, fileBuf, _IONBF, FILE_BUFFER_SIZE)!=0){ cout<<"Error at setvbuf().Failed to set buffer size for file."<<endl; memset(fileBuf, 0, sizeof(fileBuf)); closesocket(sockClient); WSACleanup(); exit(0); } //???????content???? memcpy(fileBuf, dataPackRecv.content, sizeof(dataPackRecv.content)); bytesWrite=fwrite(fileBuf, 1, sizeof(fileBuf), fwp); if(bytesWrite<sizeof(fileBuf)){ cout<<"Error at fwrite(). Failed to write the content of dataPackRecv to local file."<<endl; } //?????packCount-1????????????????? for(int i=1; i<packCount; i++){ // ????????? memset(sockBuf, 0, sizeof(sockBuf)); memset(&dataPackRecv, 0, sizeof(dataPackRecv)); memset(fileBuf, 0, sizeof(fileBuf)); SockRecv(sockClient, sockBuf); memcpy(&dataPackRecv, sockBuf, sizeof(dataPackRecv)); cout<<"???? "<<dataPackRecv.packNum<<" ?DataPack."<<endl; //???? memcpy(fileBuf, dataPackRecv.content, dataPackRecv.contenLen); bytesWrite=fwrite(fileBuf, 1, dataPackRecv.contenLen, fwp); if(bytesWrite<dataPackRecv.contenLen){ cout<<"Error at fwrite(). Failed to write the content of dataPackRecv to local file."<<endl; } } if( (i+1)==packCount ){ cout<<"??DataPack????????!"<<endl; } fclose(fwp); closesocket(sockClient); WSACleanup(); return 0;*/ }

    Read the article

  • processing an audio wav file with C

    - by sa125
    Hi - I'm working on processing the amplitude of a wav file and scaling it by some decimal factor. I'm trying to wrap my head around how to read and re-write the file in a memory-efficient way while also trying to tackle the nuances of the language (I'm new to C). The file can be in either an 8- or 16-bit format. The way I thought of doing this is by first reading the header data into some pre-defined struct, and then processing the actual data in a loop where I'll read a chunk of data into a buffer, do whatever is needed to it, and then write it to the output. #include <stdio.h> #include <stdlib.h> typedef struct header { char chunk_id[4]; int chunk_size; char format[4]; char subchunk1_id[4]; int subchunk1_size; short int audio_format; short int num_channels; int sample_rate; int byte_rate; short int block_align; short int bits_per_sample; short int extra_param_size; char subchunk2_id[4]; int subchunk2_size; } header; typedef struct header* header_p; void scale_wav_file(char * input, float factor, int is_8bit) { FILE * infile = fopen(input, "rb"); FILE * outfile = fopen("outfile.wav", "wb"); int BUFSIZE = 4000, i, MAX_8BIT_AMP = 255, MAX_16BIT_AMP = 32678; // used for processing 8-bit file unsigned char inbuff8[BUFSIZE], outbuff8[BUFSIZE]; // used for processing 16-bit file short int inbuff16[BUFSIZE], outbuff16[BUFSIZE]; // header_p points to a header struct that contains the file's metadata fields header_p meta = (header_p)malloc(sizeof(header)); if (infile) { // read and write header data fread(meta, 1, sizeof(header), infile); fwrite(meta, 1, sizeof(meta), outfile); while (!feof(infile)) { if (is_8bit) { fread(inbuff8, 1, BUFSIZE, infile); } else { fread(inbuff16, 1, BUFSIZE, infile); } // scale amplitude for 8/16 bits for (i=0; i < BUFSIZE; ++i) { if (is_8bit) { outbuff8[i] = factor * inbuff8[i]; if ((int)outbuff8[i] > MAX_8BIT_AMP) { outbuff8[i] = MAX_8BIT_AMP; } } else { outbuff16[i] = factor * inbuff16[i]; if ((int)outbuff16[i] > MAX_16BIT_AMP) { outbuff16[i] = MAX_16BIT_AMP; } else if ((int)outbuff16[i] < -MAX_16BIT_AMP) { outbuff16[i] = -MAX_16BIT_AMP; } } } // write to output file for 8/16 bit if (is_8bit) { fwrite(outbuff8, 1, BUFSIZE, outfile); } else { fwrite(outbuff16, 1, BUFSIZE, outfile); } } } // cleanup if (infile) { fclose(infile); } if (outfile) { fclose(outfile); } if (meta) { free(meta); } } int main (int argc, char const *argv[]) { char infile[] = "file.wav"; float factor = 0.5; scale_wav_file(infile, factor, 0); return 0; } I'm getting differing file sizes at the end (by 1k or so, for a 40Mb file), and I suspect this is due to the fact that I'm writing an entire buffer to the output, even though the file may have terminated before filling the entire buffer size. Also, the output file is messed up - won't play or open - so I'm probably doing the whole thing wrong. Any tips on where I'm messing up will be great. Thanks!

    Read the article

  • Win32 window capture with BitBlt not displaying border

    - by user292533
    I have written some c++ code to capture a window to a .bmp file. BITMAPFILEHEADER get_bitmap_file_header(int width, int height) { BITMAPFILEHEADER hdr; memset(&hdr, 0, sizeof(BITMAPFILEHEADER)); hdr.bfType = ((WORD) ('M' << 8) | 'B'); // is always "BM" hdr.bfSize = 0;//sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + (width * height * sizeof(int)); hdr.bfReserved1 = 0; hdr.bfReserved2 = 0; hdr.bfOffBits = (DWORD)(sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER)); return hdr; } BITMAPINFO get_bitmap_info(int width, int height) { BITMAPINFO bmi; memset(&bmi.bmiHeader, 0, sizeof(BITMAPINFOHEADER)); //initialize bitmap header bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bmi.bmiHeader.biWidth = width; bmi.bmiHeader.biHeight = height; bmi.bmiHeader.biPlanes = 1; bmi.bmiHeader.biBitCount = 4 * 8; bmi.bmiHeader.biCompression = BI_RGB; bmi.bmiHeader.biSizeImage = width * height * 4; return bmi; } void get_bitmap_from_window(HWND hWnd, int * imageBuff) { HDC hDC = GetWindowDC(hWnd); SIZE size = get_window_size(hWnd); HDC hMemDC = CreateCompatibleDC(hDC); RECT r; HBITMAP hBitmap = CreateCompatibleBitmap(hDC, size.cx, size.cy); HBITMAP hOld = (HBITMAP)SelectObject(hMemDC, hBitmap); BitBlt(hMemDC, 0, 0, size.cx, size.cy, hDC, 0, 0, SRCCOPY); //PrintWindow(hWnd, hMemDC, 0); BITMAPINFO bmi = get_bitmap_info(size.cx, size.cy); GetDIBits(hMemDC, hBitmap, 0, size.cy, imageBuff, &bmi, DIB_RGB_COLORS); SelectObject(hMemDC, hOld); DeleteDC(hMemDC); ReleaseDC(NULL, hDC); } void save_image(HWND hWnd, char * name) { int * buff; RECT r; SIZE size; GetWindowRect(hWnd, &r); size.cx = r.right-r.left; size.cy = r.bottom-r.top; buff = (int*)malloc(size.cx * size.cy * sizeof(int)); get_bitmap_from_window(hWnd, buff); BITMAPINFO bmi = get_bitmap_info(size.cx, size.cy); BITMAPFILEHEADER hdr = get_bitmap_file_header(size.cx, size.cy); FILE * fout = fopen(name, "w"); fwrite(&hdr, 1, sizeof(BITMAPFILEHEADER), fout); fwrite(&bmi.bmiHeader, 1, sizeof(BITMAPINFOHEADER), fout); fwrite(buff, 1, size.cx * size.cy * sizeof(int), fout); fflush(fout); fclose(fout); free(buff); } It works find under XP, but under Vista the border of the window is transparent. Using PrintWindow solves the problem, but is unacceptable for performance reasons. Is there a performant code change, or a setting that can be changed to make the border non-transparent?

    Read the article

  • PHP returning part of the code document

    - by The.Anti.9
    I have a PHP page that does a couple of different things depending on what action is set to in the GET data. Depending, it is supposed to return some JSON, but instead of doing anything it is supposed to it returns the bottom half of the code document itself, starting in the middle of the line. Heres the snippit from where it starts: ... } elseif ($_GET['action'] == 'addtop') { if (!isset($_GET['pname']) || !isset($_GET['url']) || !isset($_GET['artist']) || !isset($_GET['album']) || !isset($_GET['file'])) { die('Error: Incomplete data!'); } if (!file_exists($_GET['pname'].".txt")) { die('Error: No such playlist!'); } $plist = json_decode(file_get_contents($_GET['pname'].".txt"), true); $fh = fopen($_GET['pname'].".txt", 'w') or die('Could not open playlist!'); array_push($plist, array("artist" => $_GET['artist'], "album" => $_GET['album'], "file" => $_GET['file'], "url" => $_GET['url'])); fwrite($fh,json_encode($plist)); } elseif ($_GET['action'] == 'delfromp') { ... And here is what I get when I go to the page: $_GET['artist'], "album" = $_GET['album'], "file" = $_GET['file'], "url" = $_GET['url'])); fwrite($fh,json_encode($plist)); } elseif ($_GET['action'] == 'delfromp') { if (!isset($_GET['pname']) || !isset($_GET['id'])) { die('Error: Incomplete data!'); } if (!file_exists($_GET['pname'].".txt")) { die('Error: No such playlist!'); } $plist = json_decode(file_get_contents($_GET['pname'].".txt"), true); $fh = fopen($_GET['pname'].".txt", 'w') or die('Could not open playlist!'); unset($plist[$_GET['id']]); $plist = array_values($plist); fwrite($fh,json_encode($plist)); } elseif ($_GET['action'] == 'readp') { if (!file_exists($_GET['pname'].".txt")) { die('Error: No such playlist!'); } $plist = json_decode(file_get_contents($_GET['pname'].".txt"), true); $arr = array("entries" = $plist); $json = json_encode($arr); echo $json; } elseif ($_GET['action'] == 'getps') { $plists = array(); if ($handle = opendir('Playlists')) { while (false !== ($playlist = readdir($handle))) { if ($playlist != "." && $playlist != "..") { array_push($plists, substr($playlist, 0, strripos($playlist, '.')-1)); } } } else { die('Error: Can\'T open playlists!'); } $arr = array("entries"=$plists); $json = json_encode($arr); echo $json; } else { die('Error: No such action!'); } ? It starts in the middle of the array_push(... line. I really can't think of what it is doing. Theres no echos anywhere around it. Any ideas?

    Read the article

  • Generating cache file for Twitter rss feed

    - by Kerri
    I'm working on a site with a simple php-generated twitter box with user timeline tweets pulled from the user_timeline rss feed, and cached to a local file to cut down on loads, and as backup for when twitter goes down. I based the caching on this: http://snipplr.com/view/8156/twitter-cache/. It all seemed to be working well yesterday, but today I discovered the cache file was blank. Deleting it then loading again generated a fresh file. The code I'm using is below. I've edited it to try to get it to work with what I was already using to display the feed and probably messed something crucial up. The changes I made are the following (and I strongly believe that any of these could be the cause): - Revised the time difference code (the linked example seemed to use a custom function that wasn't included in the code) Removed the "serialize" function from the "fwrites". This is purely because I couldn't figure out how to unserialize once I loaded it in the display code. I truthfully don't understand the role that serialize plays or how it works, so I'm sure I should have kept it in. If that's the case I just need to understand where/how to deserialize in the second part of the code so that it can be parsed. Removed the $rss variable in favor of just loading up the cache file in my original tweet display code. So, here are the relevant parts of the code I used: <?php $feedURL = "http://twitter.com/statuses/user_timeline/#######.rss"; // START CACHING $cache_file = dirname(__FILE__).'/cache/twitter_cache.rss'; // Start with the cache if(file_exists($cache_file)){ $mtime = (strtotime("now") - filemtime($cache_file)); if($mtime > 600) { $cache_rss = file_get_contents('http://twitter.com/statuses/user_timeline/75168146.rss'); $cache_static = fopen($cache_file, 'wb'); fwrite($cache_static, $cache_rss); fclose($cache_static); } echo "<!-- twitter cache generated ".date('Y-m-d h:i:s', filemtime($cache_file))." -->"; } else { $cache_rss = file_get_contents('http://twitter.com/statuses/user_timeline/#######.rss'); $cache_static = fopen($cache_file, 'wb'); fwrite($cache_static, $cache_rss); fclose($cache_static); } //END CACHING //START DISPLAY $doc = new DOMDocument(); $doc->load($cache_file); $arrFeeds = array(); foreach ($doc->getElementsByTagName('item') as $node) { $itemRSS = array ( 'title' => $node->getElementsByTagName('title')->item(0)->nodeValue, 'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue ); array_push($arrFeeds, $itemRSS); } // the rest of the formatting and display code.... } ?> ETA 6/17 Nobody can help…? I'm thinking it has something to do with writing a blank cache file over a good one when twitter is down, because otherwise I imagine that this should be happening every ten minutes when the cache file is overwritten again, but it doesn't happen that frequently. I made the following change to the part where it checks how old the file is to overwrite it: $cache_rss = file_get_contents('http://twitter.com/statuses/user_timeline/75168146.rss'); if($mtime > 600 && $cache_rss != ''){ $cache_static = fopen($cache_file, 'wb'); fwrite($cache_static, $cache_rss); fclose($cache_static); } …so now, it will only write the file if it's over ten minutes old and there's actual content retrieved from the rss page. Do you think this will work?

    Read the article

  • C++ Serial Port Question

    - by Pfeffer
    Problem: I have a hand held device that scans those graphic color barcodes on all packaging. There is a track device that I can use that will slide the device automatically. This track device functions by taking ascii code through a serial port. I need to get this thing to work in FileMaker on a Mac. So no terminal programs, etc... What I've got so far: I bought a Keyspan USB/Serial adapter. Using a program called ZTerm I was successful in sending commands to the device. Example: "C,7^M^J" I was also able to do the same thing in Terminal using this command: screen /dev/tty.KeySerial1 57600 and then type in the same command above(but when I typed in I just hit Control-M and Control-J for the carriage return and line feed) Now I'm writing a plug-in for FileMaker(in C++ of course). I want to get what I did above happen in C++ so when I install that plug-in in FileMaker I can just call one of those functions and have the whole process take place right there. I'm able to connect to the device, but I can't talk to it. It is not responding to anything. I've tried connecting to the device(successfully) using these: FILE *comport; if ((comport = fopen("/dev/tty.KeySerial1", "w")) == NULL){...} and int fd; fd = open("/dev/tty.KeySerial1", O_RDWR | O_NOCTTY | O_NDELAY); This is what I've tried so far in way of talking to the device: fputs ("C,7^M^J",comport); or fprintf(comport,"C,7^M^J"); or char buffer[] = { 'C' , ',' , '7' , '^' , 'M' , '^' , 'J' }; fwrite (buffer , 1 , sizeof(buffer) , comport ); or fwrite('C,7^M^J', 1, 1, comport); Questions: When I connected to the device from Terminal and using ZTerm, I was able to set my baud rate of 57600. I think that may be why it isn't responding here. But I don't know how to do it here.... Does any one know how to do that? I tried this, but it didn't work: comport->BaudRate = 57600; There are a lot of class solutions out there but they all call these include files like termios.h and stdio.h. I don't have these and, for whatever reason, I can't find them to download. I've downloaded a few examples but there are like 20 files in them and they're all calling other files I can't find(like the ones listed above). Do I need to find these and if so where? I just don't know enough about C++ Is there a website where I can download libraries?? Another solution might be to put those terminal commands in C++. Is there a way to do that? So this has been driving me crazy. I'm not a C++ guy, I only know basic programming concepts. Is anyone out there a C++ expert? I ideally I'd like this to just work using functions I already have, like those fwrite, fputs stuff. Thanks!

    Read the article

  • Single use download script - Modification [on hold]

    - by Iulius
    I have this Single use download script! This contain 3 php files: page.php , generate.php and variables.php. Page.php Code: <?php include("variables.php"); $key = trim($_SERVER['QUERY_STRING']); $keys = file('keys/keys'); $match = false; foreach($keys as &$one) { if(rtrim($one)==$key) { $match = true; $one = ''; } } file_put_contents('keys/keys',$keys); if($match !== false) { $contenttype = CONTENT_TYPE; $filename = SUGGESTED_FILENAME; readfile(PROTECTED_DOWNLOAD); exit; } else { ?> <html> <head> <meta http-equiv="refresh" content="1; url=http://docs.google.com/"> <title>Loading, please wait ...</title> </head> <body> Loading, please wait ... </body> </html> <?php } ?> Generate.php Code: <?php include("variables.php"); $password = trim($_SERVER['QUERY_STRING']); if($password == ADMIN_PASSWORD) { $new = uniqid('key',TRUE); if(!is_dir('keys')) { mkdir('keys'); $file = fopen('keys/.htaccess','w'); fwrite($file,"Order allow,deny\nDeny from all"); fclose($file); } $file = fopen('keys/keys','a'); fwrite($file,"{$new}\n"); fclose($file); ?> <html> <head> <title>Page created</title> <style> nl { font-family: monospace } </style> </head> <body> <h1>Page key created</h1> Your new single-use page link:<br> <nl> <?php echo "http://" . $_SERVER['HTTP_HOST'] . DOWNLOAD_PATH . "?" . $new; ?></nl> </body> </html> <?php } else { header("HTTP/1.0 404 Not Found"); } ?> And the last one Variables.php Code: <? define('PROTECTED_DOWNLOAD','download.php'); define('DOWNLOAD_PATH','/.work/page.php'); define('SUGGESTED_FILENAME','download-doc.php'); define('ADMIN_PASSWORD','1234'); define('EXPIRATION_DATE', '+36 hours'); header("Cache-Control: no-cache, must-revalidate"); header("Expires: ".date('U', strtotime(EXPIRATION_DATE))); ?> The http://www.site.com/generate.php?1234 will generate a unique link like page.php?key1234567890. This link page.php?key1234567890 will be sent by email to my user. Now how can I generate a link like this page.php?key1234567890&[email protected] ? So I think I must access the generator page like this generate.php?1234&[email protected] . P.S. This variable will be posted on the download page by "Hello, " I tried everthing to complete this, and no luck. Thanks in advance for help.

    Read the article

  • Trying to save file from Flash to PHP using $GLOBALS["HTTP_RAW_POST_DATA"]

    - by jolyonruss
    Let me start by saying PHP isn't my forte, I'm usually reluctant to try working with it because of problems exactly like this. The code works fine on my local machine under MAMP and on my server, but doesn't on the clients server :'( So what am I trying to do, well - save an image from Flash onto the server, simple right?! I'm using the method described on this site here: http://designreviver.com/tutorials/actionscript-3-jpeg-encoder-revealed-saving-images-from-flash/ but have made a small alteration so that instead of echoing the jpg causing the browser to download it locally, I do an fwrite and an fclose to save it to the server. Here is my PHP: $imageFile = '../images/' . $_GET['name']; $imageHandle = fopen($imageFile, "w"); fwrite($imageHandle, $jpg); fclose($imageHandle); } ? I've dona a phpinfo() on my clients server and it's running 5.2.2 my host is running 5.2.11 I don't know if much can have changed in those 9 minor revisions? I've also read another question on here which suggests making suer always_populate_raw_post_data is set to ON, but it's set to OFF on all of the server environments I've been testing in. I'm doing some XML saving using file_get_contents('php://input') which I've tried but failed to get working with images. Any help would be gratefully received, I'm happy to post the AS3 as well but it's EXACTLY the same as example I've linked above and works locally. As far as I can tell the problem lies with the PHP. Cheers.

    Read the article

  • Using PHP to store results of a post request

    - by Paul M
    Im currently working with an API which requires we send our collection details in xml to their server using a post request. Nothing major there but its not working, so I want to output the sent xml to a txt file so I can look at actually whats being sent!! Instead of posting to the API im posting to a document called target, but the xml its outputting its recording seems to be really wrong. Here is my target script, note that the posting script posts 3 items, so the file being written should have details of each post request one after the other. <?php error_reporting(E_ALL); ini_set('display_errors', 1); // get the request data... $payload = ''; $fp = fopen('php://input','r'); $output_file = fopen('output.txt', 'w'); while (!feof($fp)) { $payload .= fgets($fp); fwrite($output_file, $payload); } fclose($fp); fclose($output_file); ?> I also tried the following, but this just recorded the last post request so only 1 collection item was recorded in the txt file, instead of all 3 output_file = fopen('output.txt', 'w'); while (!feof($fp)) { $payload .= fgets($fp); } fwrite($output_file, $payload); fclose($fp); fclose($output_file); I know im missing something really obvious, but ive been looking at this all morning!

    Read the article

  • mEncrypt/Decrypt binary mp3 with mcrypt, missing mimetype

    - by Jeremy Dicaire
    I have a script that read a mp3 file and encrypt it, I want to be able to decrypt this file and convert it to base64 so it can play in html5. Key 1 will be stored on the page and static, key2 will be unique for each file, for testing I used: $key1 = md5(time()); $key2 = md5($key1.time()); Here is my encode php code : //Get file content $file = file_get_contents('test.mp3'); //Encrypt file $Encrypt = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key1, $file, MCRYPT_MODE_CBC, $key2); $Encrypt = trim(base64_encode($Encrypt)); //Create new file $fileE = "test.mp3e"; $fileE = fopen($file64, 'w') or die("can't open file"); //Put crypted content fwrite($fileE, $Encrypt); //Close file fclose($fileE); Here is the code that doesnt work (decoded file is same size, but no mimetype): //Get file content $fileE = file_get_contents('test.mp3e'); //Decode $fileDecoded = base64_decode($fileE); //Decrypt file $Decrypt = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key1, $fileDecoded, MCRYPT_MODE_CBC, $key2); $Decrypt = trim($Decrypt); //Create new file $file = "test.mp3"; $file = fopen($file, 'w') or die("can't open file"); //Put crypted content fwrite($file, $Decrypt); //Close file fclose($file);

    Read the article

  • download file, without saving in server

    - by lolalola
    Hi, Or possible for users to download the file without saving it on the server? I am getting data from the database, and I want to save them .doc (MS Word) file. if(isset($_POST['save'])) { $file = "new_file2.doc"; $stringData = "Text text text text...."; //This data put in new Word file $fh = fopen($file, 'w'); fwrite($fh, $stringData); fclose($fh); header('Content-Description: File Transfer'); header('Content-type: application/msword'); header('Content-Disposition: attachment; filename="'.$file.'"'); header('Content-Transfer-Encoding: binary'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); header('Content-Length: ' . filesize($file)); ob_clean(); flush(); readfile($file); unlink($file); exit; } How should the code look like without this: " $fh = fopen($file, 'w'); fwrite($fh, $stringData); fclose($fh);" and this "unlink($file);" I hope to understand what I need enter code here

    Read the article

  • Wordpress paths issue

    - by Martin
    I have set a crawler up in wordpress which grabs stocks data and writes to file which when a user enters a symbol/ticker the variable is read and if it matches the data of a previous crawl for that particular companies data will echo the text file on page, if no data is found the crawler then sets off grabs it and writes to file to save for the next time that symbol is used. The problem im having is that everything works groovey apart from one thing, when the content is written to file it saves it in the WP root and not inside a subfolder of the theme, basicaly this means that root becomes untidy very quickly and also should the theme be used on another site then its not practical as some important info is missing. I have tried bloginfo and absolute both return the same failure. This is the code i am using to write to file, like i say it works apart from writing the file into root. <?php $CompDetails = "http://www.devserverurl.com/mattv1/wp-content/themes/stocks/tools/modules/Stock_Quote/company_details/$Symbol.txt"; if (file_exists($CompDetails)) {} else { include ('crawler_file.php'); $html = file_get_html("http://targeturl.com/research/stocks/snapshot/snapshot.asp?ticker=$Symbol:US"); $es = $html->find('div[class="detailsDataContainerLt"]'); $tickerdetails = ("$es[0]"); $FileHandle2 = fopen($CompDetails, 'w') or die("can't open file"); fwrite($FileHandle2, $tickerdetails); fclose($FileHandle2); } ?> edit below, have also tried this and the same happens as above <?php if (file_exists($_SERVER['DOCUMENT_ROOT'] . "/wp-content/themes/stocks/tools/modules/Stock_Quote/company_details/$Symbol.txt")) {} else { include ('crawler_file.php'); $html = file_get_html("http://targeturl.com/research/stocks/snapshot/snapshot.asp?ticker=$Symbol:US"); $es = $html->find('div[class="detailsDataContainerLt"]'); $tickerdetails = ("$es[0]"); $FileHandle2 = fopen($_SERVER['DOCUMENT_ROOT'] . "/wp-content/themes/stocks/tools/modules/Stock_Quote/company_details/$Symbol.txt", 'w') or die("can't open file"); fwrite($FileHandle2, $tickerdetails); fclose($FileHandle2); } ?>

    Read the article

  • unicode convertion problem

    - by bhoomi-nature
    Hai frnds i am bhoomi new to php,i am having having below problem in my coding please can you help anyone 1.first i want to open one word document which is having content and i wann to edit it 2.for that i am opening word document from the server and at that time its opening with garbage value(i thing its not converting to utf8 format) 3.wen i delete that garbage value and insert something from textarea to that file it is going to insert and next time onwords its its getting open properly. 4.actually i wann that doc file should open with english words wats there in that doc instead of garbage value..first time opening only its giving problem. i am using below code for that please do the needful $filename = 'test.doc'; if(isset($_REQUEST['Submit'])){ $somecontent = stripslashes($_POST['somecontent']); // Let's make sure the file exists and is writable first. if (is_writable($filename)) { // In our example we're opening $filename in append mode. // The file pointer is at the bottom of the file hence // that's where $somecontent will go when we fwrite() it. if (!$handle = fopen($filename, 'w')) { echo "Cannot open file ($filename)"; exit; } // Write $somecontent to our opened file. if (fwrite($handle, $somecontent) === FALSE) { echo "Cannot write to file ($filename)"; exit; } echo "Success, wrote ($somecontent) to file ($filename) - Continue - "; fclose($handle); } else { echo "The file $filename is not writable"; } } else{ // get contents of a file into a string $handle = fopen($filename, 'r'); $somecontent = fread($handle, filesize($filename)); ? Edit file

    Read the article

  • opening word document contailning macros using textarea

    - by avani-nature
    Hai frnds i am avani here,actually 1.i amhaving one word document which contains macros i wann to open it in textarea.. 2.i am able to open the word document which is not containing macros 3.i am not able to open the document which contains macros 4.i am using below code 5.please do help me anyone i am thinking its some what impossible { //echo $aud; $filename = 'C:/xampp/htdocs/mts/sites/default/files/a.doc'; //echo $filename; if(isset($_REQUEST['Save'])){ $somecontent = stripslashes($_POST['somecontent']); // Let's make sure the file exists and is writable first. if (is_writable($filename)) { // In our example we're opening $filename in append mode. // The file pointer is at the bottom of the file hence // that's where $somecontent will go when we fwrite() it. if (!$handle = fopen($filename, 'w')) { echo "Cannot open file ($filename)"; exit; } // Write $somecontent to our opened file. if (fwrite($handle, $somecontent) === FALSE) { echo "Cannot write to file ($filename)"; exit; } echo "Success, wrote ($somecontent) to file ($filename) - Continue - "; fclose($handle); } else { echo "The file $filename is not writable"; } } else{ // get contents of a file into a string $handle = fopen($filename, "r"); $somecontent = fread($handle, filesize($filename)); $word = new COM("word.application") or die ("Could not initialise MS Word object."); $word-Documents-Open(realpath("$filename")); // Extract content. $somecontent = (string) $word-ActiveDocument-Content; //echo $somecontent; $word-ActiveDocument-Close(false); $word-Quit(); $word = null; unset($word); fclose($handle); } ? Edit file -------- ?

    Read the article

  • php_network_getaddresses: getaddrinfo failed: Name or service not known

    - by Rob
    Here is a snippet of my code $fp = fsockopen($s['url'], 80, $errno, $errstr, 5); if($fp){ fwrite($fp, $out); fclose($fp); When I run it, it outputs: unable to connect to www.mydomain.net/1/file.php:80 (php_network_getaddresses: getaddrinfo failed: Name or service not known I can't figure out why. Any help would be greatly appreciated. EDIT: I forgot to mention that I'm using this to submit GET data to the $s['url']

    Read the article

  • GDI+ crashes when loading PNG from IStream

    - by konforce
    I wrote something to load PNG files from a custom C++ IStream via GDI+. It worked great until I ran it on Vista machines. Crashes every time. When compiled on VS 2008, I found that inserting code into the IStream::AddRef method, such as a cout, made the problem go away. When compiling with VS 2010, it still crashes regardless of that. I stripped the program down to its basics. I copied a FileStream straight from Microsoft's documentation. It can load PNGs when using Bitmap::FromFile. It can load JPEGs, GIFs, and BMPs via FromFile or FromStream. So in short: on Vista, PNG files loaded via Bitmap::FromStream crash. #pragma comment(lib, "gdiplus.lib") #include <iostream> #include <objidl.h> #include <gdiplus.h> class FileStream : public IStream { public: FileStream(HANDLE hFile) { _refcount = 1; _hFile = hFile; } ~FileStream() { if (_hFile != INVALID_HANDLE_VALUE) { ::CloseHandle(_hFile); } } public: HRESULT static OpenFile(LPCWSTR pName, IStream ** ppStream, bool fWrite) { HANDLE hFile = ::CreateFileW(pName, fWrite ? GENERIC_WRITE : GENERIC_READ, FILE_SHARE_READ, NULL, fWrite ? CREATE_ALWAYS : OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile == INVALID_HANDLE_VALUE) return HRESULT_FROM_WIN32(GetLastError()); *ppStream = new FileStream(hFile); if(*ppStream == NULL) CloseHandle(hFile); return S_OK; } virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void ** ppvObject) { if (iid == __uuidof(IUnknown) || iid == __uuidof(IStream) || iid == __uuidof(ISequentialStream)) { *ppvObject = static_cast<IStream*>(this); AddRef(); return S_OK; } else return E_NOINTERFACE; } virtual ULONG STDMETHODCALLTYPE AddRef(void) { return (ULONG)InterlockedIncrement(&_refcount); } virtual ULONG STDMETHODCALLTYPE Release(void) { ULONG res = (ULONG) InterlockedDecrement(&_refcount); if (res == 0) delete this; return res; } // ISequentialStream Interface public: virtual HRESULT STDMETHODCALLTYPE Read(void* pv, ULONG cb, ULONG* pcbRead) { ULONG local_pcbRead; BOOL rc = ReadFile(_hFile, pv, cb, &local_pcbRead, NULL); if (pcbRead) *pcbRead = local_pcbRead; return (rc) ? S_OK : HRESULT_FROM_WIN32(GetLastError()); } virtual HRESULT STDMETHODCALLTYPE Write(void const* pv, ULONG cb, ULONG* pcbWritten) { BOOL rc = WriteFile(_hFile, pv, cb, pcbWritten, NULL); return rc ? S_OK : HRESULT_FROM_WIN32(GetLastError()); } // IStream Interface public: virtual HRESULT STDMETHODCALLTYPE SetSize(ULARGE_INTEGER) { return E_NOTIMPL; } virtual HRESULT STDMETHODCALLTYPE CopyTo(IStream*, ULARGE_INTEGER, ULARGE_INTEGER*, ULARGE_INTEGER*) { return E_NOTIMPL; } virtual HRESULT STDMETHODCALLTYPE Commit(DWORD) { return E_NOTIMPL; } virtual HRESULT STDMETHODCALLTYPE Revert(void) { return E_NOTIMPL; } virtual HRESULT STDMETHODCALLTYPE LockRegion(ULARGE_INTEGER, ULARGE_INTEGER, DWORD) { return E_NOTIMPL; } virtual HRESULT STDMETHODCALLTYPE UnlockRegion(ULARGE_INTEGER, ULARGE_INTEGER, DWORD) { return E_NOTIMPL; } virtual HRESULT STDMETHODCALLTYPE Clone(IStream **) { return E_NOTIMPL; } virtual HRESULT STDMETHODCALLTYPE Seek(LARGE_INTEGER liDistanceToMove, DWORD dwOrigin, ULARGE_INTEGER* lpNewFilePointer) { DWORD dwMoveMethod; switch(dwOrigin) { case STREAM_SEEK_SET: dwMoveMethod = FILE_BEGIN; break; case STREAM_SEEK_CUR: dwMoveMethod = FILE_CURRENT; break; case STREAM_SEEK_END: dwMoveMethod = FILE_END; break; default: return STG_E_INVALIDFUNCTION; break; } if (SetFilePointerEx(_hFile, liDistanceToMove, (PLARGE_INTEGER) lpNewFilePointer, dwMoveMethod) == 0) return HRESULT_FROM_WIN32(GetLastError()); return S_OK; } virtual HRESULT STDMETHODCALLTYPE Stat(STATSTG* pStatstg, DWORD grfStatFlag) { if (GetFileSizeEx(_hFile, (PLARGE_INTEGER) &pStatstg->cbSize) == 0) return HRESULT_FROM_WIN32(GetLastError()); return S_OK; } private: volatile HANDLE _hFile; volatile LONG _refcount; }; #define USE_STREAM int main() { Gdiplus::GdiplusStartupInput gdiplusStartupInput; ULONG_PTR gdiplusToken; Gdiplus::GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL); Gdiplus::Bitmap *bmp; #ifndef USE_STREAM bmp = Gdiplus::Bitmap::FromFile(L"test.png", false); if (!bmp) { std::cerr << " Unable to open image file." << std::endl; return 1; } #else IStream *s; if (FileStream::OpenFile(L"test.png", &s, false) != S_OK) { std::cerr << "Unable to open image file." << std::endl; return 1; } bmp = Gdiplus::Bitmap::FromStream(s, false); #endif std::cout << "Image is " << bmp->GetWidth() << " by " << bmp->GetHeight() << std::endl; Gdiplus::GdiplusShutdown(gdiplusToken); #ifdef USE_STREAM s->Release(); #endif return 0; } Tracing and debugging, shows that it does make some calls to the IStream class. It crashes inside of lastResult = DllExports::GdipCreateBitmapFromStream(stream, &bitmap); from GdiPlusBitmap.h, which is a static inline wrapper over the flat API. Other than the reference counting, the only IStream methods it calls is stat (for file size), read, and seek. Call stack looks like: ntdll.dll!_DbgBreakPoint@0() + 0x1 bytes ntdll.dll!_RtlpBreakPointHeap@4() + 0x28 bytes ntdll.dll!_RtlpValidateHeapEntry@12() + 0x70a3c bytes ntdll.dll!_RtlDebugFreeHeap@12() + 0x9a bytes ntdll.dll!@RtlpFreeHeap@16() + 0x13cdd bytes ntdll.dll!_RtlFreeHeap@12() + 0x2e49 bytes kernel32.dll!_HeapFree@12() + 0x14 bytes ole32.dll!CRetailMalloc_Free() + 0x1c bytes ole32.dll!_CoTaskMemFree@4() + 0x13 bytes GdiPlus.dll!GpPngDecoder::GetImageInfo() + 0x68 bytes GdiPlus.dll!GpDecodedImage::InternalGetImageInfo() + 0x3c bytes GdiPlus.dll!GpDecodedImage::GetImageInfo() + 0x18 bytes GdiPlus.dll!CopyOnWriteBitmap::CopyOnWriteBitmap() + 0x49 bytes GdiPlus.dll!CopyOnWriteBitmap::Create() + 0x1d bytes GdiPlus.dll!GpBitmap::GpBitmap() + 0x2c bytes I was unable to find anybody else with the same problem, so I assume there's something wrong with my implementation...

    Read the article

  • PHP Mcrypt - Encrypting / Decrypting file

    - by whitman6732
    Trying to write a couple of functions that will encrypt or decrypt a file and am using the class found here to try and accomplish this: http://www.itnewb.com/v/PHP-Encryption-Decryption-Using-the-MCrypt-Library-libmcrypt The encryption function below seems to work, in that it appears to encrypt the file and place it in the intended directory. I'm trying to decrypt the file now, and it just dies with the message "Failed to complete decryption" (which is coded in there...) There's nothing in the php error logs, so I'm not sure why it's failing, but as mcrypt is entirely new to me, I'm more than inclined to believe I'm doing something wrong here... Here are the functions: //ENCRYPT FILE function encryptFile() { global $cryptastic; $pass = PGPPASS; $salt = PGPSALT; $key = $cryptastic->pbkdf2($pass, $salt, 1000, 32) or die("Failed to generate secret key."); if ($handle = opendir(PATH.'/ftpd')) { while (false !== ($file = readdir($handle))) { if ($file != "." && $file != "..") { $newfile = PATH.'/encrypted/'.$file.'.txt'; $msg = file_get_contents(PATH.'/ftpd/'.$file); $encrypted = $cryptastic->encrypt($msg, $key) or die("Failed to complete encryption."); $nfile = fopen($newfile, 'w'); fwrite($nfile, $encrypted); fclose($nfile); unlink(PATH.'/ftpd/'.$file); } } closedir($handle); } //DECRYPT FILE function inFTP() { global $cryptastic; $pass = PGPPASS; $salt = PGPSALT; $key = $cryptastic->pbkdf2($pass, $salt, 1000, 32) or die("Failed to generate secret key."); if ($handle = opendir(PATH.'/encrypted')) { while (false !== ($file = readdir($handle))) { if ($file != "." && $file != "..") { $newfile = PATH.'/decrypted/'.$file; $msg = PATH.'/encrypted/'.$file; $decrypted = $cryptastic->decrypt($msg, $key) or die("Failed to complete decryption."); $nfile = fopen($newfile, 'w'); fwrite($nfile, $decrypted); fclose($nfile); //unlink(PATH.'/encrypted/'.$file); } } closedir($handle); } //$crypt->decrypt($file); }

    Read the article

  • properies profile when writing word file

    - by avani-nature
    Hai frnds i am new to php i am having following problems in my coding... 1.Actually i am opening word document with com object and storing it in textarea. 2.when content gets opened in textarea i am editing that content and saving the document 3.actually when i edited that file and done save after that if i open word document then file properties-custom the old content getting removed i wannt to retain that even if i edited the word document..please do the needful i am using below code <?php $filename = 'C:/xampp/htdocs/mts/sites/default/files/a.doc'; //echo $filename; if(isset($_REQUEST['Save'])){ $somecontent = stripslashes($_POST['somecontent']); // Let's make sure the file exists and is writable first. if (is_writable($filename)) { // In our example we're opening $filename in append mode. // The file pointer is at the bottom of the file hence // that's where $somecontent will go when we fwrite() it. if (!$handle = fopen($filename, 'w')) { echo "Cannot open file ($filename)"; exit; } // Write $somecontent to our opened fi<form action="" method="get"></form>le. if (fwrite($handle, $somecontent) === FALSE) { echo "Cannot write to file ($filename)"; exit; } echo "Success, wrote ($somecontent) to file ($filename) <a href=".$_SERVER['PHP_SELF']."> - Continue - "; fclose($handle); } else { echo "The file $filename is not writable"; } } else{ // get contents of a file into a string $handle = fopen($filename, "r"); $somecontent = fread($handle, filesize($filename)); $word = new COM("word.application") or die ("Could not initialise MS Word object."); $word->Documents->Open(realpath("$filename")); // Extract content. $somecontent = (string) $word->ActiveDocument->Content; //echo $somecontent; $word->ActiveDocument->Close(false); $word->Quit(); $word = null; unset($word); fclose($handle); } ?> <h6>Edit file --------><? $filenam=explode("/",$filename);$filename=$filename[7]; echo $filename ;?></h6> <form name="form1" method="post" action=""> <p> <textarea name="somecontent" cols="100" rows="20"><? echo $somecontent ;?></textarea> </p> <div style='padding-left:250px;'><input type="submit" name="Save" value="Save"></div> </p> </form> <? } ?>

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9  | Next Page >