2013년 2월 15일 금요일

[c/c++]파일복사

// 아래의 예제는 파일을 fread()와 fwrite()를 이용한
// 파일 복사를 하는 예입니다.

#include 

int main( void)
{
   FILE    *fp_sour;    // 파일 원본을 위한 파일 스트림 포인터
   FILE    *fp_dest;    // 복사 대상을 위한 파일 스트림 포인터
   char     buff[1024]; // 파일 내요을 읽기/쓰기를 위한 버퍼
   size_t   n_size;     // 읽거나 쓰기를 위한 데이터의 개수
                                          
   fp_sour  = fopen( "./main.c"  , "r");
   fp_dest  = fopen( "./main.bck", "w");
                            
   while( 0 < (n_size = fread( buff, 1, 1024, fp_sour)))
   {
      fwrite( buff, 1, n_size, fp_dest);
   }                            

   fclose( fp_sour);
   fclose( fp_dest);
   return 0;
}

2013년 2월 13일 수요일

dir

http://www.dreamincode.net/forums/topic/59943-accessing-directories-in-cc-part-i/
#include  // directory header
#include  // printf()
#include  // exit()

int main () // entry point of the program
{
    // first off, we need to create a pointer to a directory
    DIR *pdir = NULL; // remember, it's good practice to initialise a pointer to NULL!
    struct dirent *pent = NULL;

    // I used the current directory, since this is one which will apply to anyone reading
    // this tutorial~ If I said "C:\\" and you're on Linux, it may get a little confusing!
    pdir = opendir ("."); // "." will refer to the current directory
    if (pdir == NULL) // if pdir wasn't initialised correctly
    { // print an error message and exit the program
        printf ("\nERROR! pdir could not be initialised correctly");
        exit (3);
    } // end if

    while (pent = readdir (pdir)) // while there is still something in the directory to list
    {
        if (pent == NULL) // if pent has not been initialised correctly
        { // print an error message, and exit the program
            printf ("ERROR! pent could not be initialised correctly");
            exit (3);
 }
 // otherwise, it was initialised correctly. let's print it on the console:
        printf ("%s\n", pent->d_name);
    }
    // finally, let's close the directory
    closedir (pdir);
return 0;

// everything went OK
}

1


2013년 2월 7일 목요일

winsock2 socket

// winhide.cpp : Defines the entry point for the application.
//

#include "stdafx.h"
#include "resource.h"

#include 

using namespace std;

#define MAX_LOADSTRING 100
#define DEFAULT_PORT 80

// Global Variables:
HINSTANCE hInst;        // current instance
TCHAR szTitle[MAX_LOADSTRING];        // The title bar text
TCHAR szWindowClass[MAX_LOADSTRING];        // The title bar text

// Foward declarations of functions included in this code module:
ATOM    MyRegisterClass(HINSTANCE hInstance);
BOOL    InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
LRESULT CALLBACK About(HWND, UINT, WPARAM, LPARAM);

int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR     lpCmdLine,
                     int       nCmdShow)
{
  // TODO: Place code here.
 MSG msg;
 HACCEL hAccelTable;

 // Initialize global strings
 LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
 LoadString(hInstance, IDC_WINHIDE, szWindowClass, MAX_LOADSTRING);
 MyRegisterClass(hInstance);

 // Perform application initialization:
 if (!InitInstance (hInstance, nCmdShow)) 
 {
  return FALSE;
 }

 hAccelTable = LoadAccelerators(hInstance, (LPCTSTR)IDC_WINHIDE);

 // Main message loop:
 while (GetMessage(&msg, NULL, 0, 0)) 
 {
  if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) 
  {
   TranslateMessage(&msg);
   DispatchMessage(&msg);
  }
 }

 return msg.wParam;
}



//
//  FUNCTION: MyRegisterClass()
//
//  PURPOSE: Registers the window class.
//
//  COMMENTS:
//
//    This function and its usage is only necessary if you want this code
//    to be compatible with Win32 systems prior to the 'RegisterClassEx'
//    function that was added to Windows 95. It is important to call this function
//    so that the application will get 'well formed' small icons associated
//    with it.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
 WNDCLASSEX wcex;

 wcex.cbSize = sizeof(WNDCLASSEX); 

 wcex.style   = CS_HREDRAW | CS_VREDRAW;
 wcex.lpfnWndProc = (WNDPROC)WndProc;
 wcex.cbClsExtra  = 0;
 wcex.cbWndExtra  = 0;
 wcex.hInstance  = hInstance;
 wcex.hIcon   = LoadIcon(hInstance, (LPCTSTR)IDI_WINHIDE);
 wcex.hCursor  = LoadCursor(NULL, IDC_ARROW);
 wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
 wcex.lpszMenuName = (LPCSTR)IDC_WINHIDE;
 wcex.lpszClassName = szWindowClass;
 wcex.hIconSm  = LoadIcon(wcex.hInstance, (LPCTSTR)IDI_SMALL);

 return RegisterClassEx(&wcex);
}

//
//   FUNCTION: InitInstance(HANDLE, int)
//
//   PURPOSE: Saves instance handle and creates main window
//
//   COMMENTS:
//
//        In this function, we save the instance handle in a global variable and
//        create and display the main program window.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
   HWND hWnd;

   hInst = hInstance; // Store instance handle in our global variable

   hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
      CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);

   if (!hWnd)
   {
      return FALSE;
   }

   ShowWindow(hWnd, SW_SHOW);
   UpdateWindow(hWnd);

   hisocket();

   return TRUE;
}

//
//  FUNCTION: WndProc(HWND, unsigned, WORD, LONG)
//
//  PURPOSE:  Processes messages for the main window.
//
//  WM_COMMAND - process the application menu
//  WM_PAINT - Paint the main window
//  WM_DESTROY - post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
 int wmId, wmEvent;
 PAINTSTRUCT ps;
 HDC hdc;
 TCHAR szHello[MAX_LOADSTRING];
 LoadString(hInst, IDS_HELLO, szHello, MAX_LOADSTRING);

 switch (message) 
 {
  case WM_COMMAND:
   wmId    = LOWORD(wParam); 
   wmEvent = HIWORD(wParam); 
   // Parse the menu selections:
   switch (wmId)
   {
    case IDM_ABOUT:
       DialogBox(hInst, (LPCTSTR)IDD_ABOUTBOX, hWnd, (DLGPROC)About);
       break;
    case IDM_EXIT:
       DestroyWindow(hWnd);
       break;
    default:
       return DefWindowProc(hWnd, message, wParam, lParam);
   }
   break;
  case WM_PAINT:
   hdc = BeginPaint(hWnd, &ps);
   // TODO: Add any drawing code here...
   RECT rt;
   GetClientRect(hWnd, &rt);
   DrawText(hdc, szHello, strlen(szHello), &rt, DT_CENTER);
   EndPaint(hWnd, &ps);
   break;
  case WM_DESTROY:
   PostQuitMessage(0);
   break;
  default:
   return DefWindowProc(hWnd, message, wParam, lParam);
   }
   return 0;
}

// Mesage handler for about box.
LRESULT CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
 switch (message)
 {
  case WM_INITDIALOG:
    return TRUE;

  case WM_COMMAND:
   if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) 
   {
    EndDialog(hDlg, LOWORD(wParam));
    return TRUE;
   }
   break;
 }
    return FALSE;
}


int hisocket() {

    //----------------------
    // Declare and initialize variables.
    int iResult;
    WSADATA wsaData;

    SOCKET ConnectSocket = INVALID_SOCKET;
    struct sockaddr_in clientService;

    int recvbuflen = DEFAULT_BUFLEN;
    string request;
 request += "GET / HTTP/1.1 \r\n";
 request += "Host:www.naver.com\r\n";
 request += "\r\n";
 
 char recvbuf[DEFAULT_BUFLEN] = "";

    //----------------------
    // Initialize Winsock
    iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    if (iResult != NO_ERROR) {
    //    wprintf(L"WSAStartup failed with error: %d\n", iResult);
        return 1;
    }

    //----------------------
    // Create a SOCKET for connecting to server
    ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (ConnectSocket == INVALID_SOCKET) {
      //  wprintf(L"socket failed with error: %ld\n", WSAGetLastError());
        WSACleanup();
        return 1;
    }

    //----------------------
    // The sockaddr_in structure specifies the address family,
    // IP address, and port of the server to be connected to.
    clientService.sin_family = AF_INET;
   // clientService.sin_addr.s_addr = inet_addr( "180.70.134.19" );
    clientService.sin_port = htons(DEFAULT_PORT);
 
 struct hostent* g_szIpAddress;
 g_szIpAddress = gethostbyname("www.naver.com");
    clientService.sin_addr.s_addr=*(LPDWORD)g_szIpAddress->h_addr_list[0];
    
    //----------------------
    // Connect to server.
    iResult = connect( ConnectSocket, (SOCKADDR*) &clientService, sizeof(clientService) );
    if (iResult == SOCKET_ERROR) {
        //wprintf(L"connect failed with error: %d\n", WSAGetLastError() );
        closesocket(ConnectSocket);
        WSACleanup();
        return 1;
  }

    //----------------------
    // Send an initial buffer
    iResult = send( ConnectSocket, request.c_str(), request.length(), 0 );
    if (iResult == SOCKET_ERROR) {
      //  wprintf(L"send failed with error: %d\n", WSAGetLastError());
        closesocket(ConnectSocket);
        WSACleanup();
        return 1;
    }

   // printf("Bytes Sent: %d\n", iResult);

   // Receive until the peer closes the connection
 FILE *fd;
    fd=fopen("receved.txt","w+");

 do{
 iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
    int i;

 //받은파일 내용 출력/저장.
 for(i=0; i <=iResult ; i++)
 {
   fprintf(fd,"%c", recvbuf[i]);
 }
 
 } while (iResult>0);

    // close the socket
    iResult = closesocket(ConnectSocket);
    if (iResult == SOCKET_ERROR) {
      //  wprintf(L"close failed with error: %d\n", WSAGetLastError());
        WSACleanup();
        return 1;
    }

    WSACleanup();
    return 0;
}

베르누이식


유체역학은 기본적으로 뉴턴 역학에 기초를 두고 있다. 따라서 베르누이 방정식을 유도하기 위해서, 흐름관 단면 내의 유체에 일-에너지 정리를 이용하여 유도 가능하다.
<베르누이 방정식 유도>
어떤 시간에 두 단면 a와 c 사이에 놓여 있는 유체를 고려한다. 낮은 쪽 끝에서 유체의 속력이 이고 압력은 이다. 그리고 임의의 짧은 시간 간격 dt 동안 초기에 a에 이던 유체는 b 까지, 거리 를 움직인다. 이때 같은 시간 간격 동안 c에 있던 유체는 d 까지 거리 를 움직인다.
양 끝에서 단면적은 보는 바와 같이 와 이며, 연속적인 관계 때문에 dt 동안 두 단면을 통과하는 유체의 부피는 이다.
이제 dt 동안 이 유체에 한 일을 계산해 보자. a에서 단명에 작용하는 힘은 이고, c에서 힘은이다. 여기서 과 는 양 끝에서의 압력이다. 따라서 이 변위 동안에 한 일의 양 dW는
이다. 여기서 음의 부호는 c에서 힘은 변위가 반대 방향이기 때문이다.
이 일을 이제, 유체소에 대한 역학적 에너지 즉, 운동에너지와 위치에너지에 관해 서술해 보자.
단면 b와 c사이의 유체에 대한 역학적 에너지는 변하지 않는다. dt시간 초기에 a와 b 사이의 유체는 부피가 , 질량이  그리고 운동에너지는 이다. 마찬가지로 c와 d 사이에서 유체의 운동에너지는 이다. 따라서 이 시간동안 운동에너지의 총 변화 dK는
이다. 동일한 방법을 적용하여 위치에너지의 변화 dU를 구하면
이다. 운동량의 변화량과 위치에너지의 변화량의 합은 총 한 일의 변화량과 같음으로dW=dK+dU에 각각 대입하면 다음을 얻을 수 있다.
이것이 베르누이 방정식이다.

연속방정식 $$
A_{1}v_{1}=A_{2}v_{2}

$$
역학적 에너지 보존
$$
\\P_{2}V_{2}-P_{1}V_{1}=\frac{1}{2}\rho V_{2}v_{2}^{2}-\frac{1}{2}\rho V_{1}v_{1}^{2}
$$
연속방정식을 대입하여 정리
$$
\\P_{2}-P_{1}\frac{V_{2}}{V_{1}}=\frac{1}{2}\rho v_{2}^{2}-\frac{1}{2}\rho \frac{V_{2}}{V_{1}v_{1}^{2}}
$$

2013년 2월 6일 수요일

perl socket another

use Socket;
use FileHandle;

$iaddr = inet_aton($ARGV[0]);
$paddr = sockaddr_in($ARGV[1],$iaddr);

$proto = getprotobyname("tcp");

socket (FHOST, PF_INET, SOCK_STREAM, $proto) or
                 die ("no free sockets\n");
connect (FHOST, $paddr)  or
                 die ("$ARGV[0] is not responding\n");

# turn buffering off

autoflush FHOST 1;

# dialogue

print FHOST "GET / HTTP/1.1 
Host:www.naver.com\n\n";

@response = ;

$rpage = join("",@response);
$rpage =~ s/\r\n/\n/g;
$rpage =~ s/\r/\n/g;
($header,$page) = split(/\n\n/,$rpage,2);
print $header;
@tags = ($page =~ /<(.*?)>/gs);

foreach (@tags) {
        s/\s*=\s*/=/g;
        @params = split(/\s+/);
        $type = lc(shift @params);
        next if ($type ne "a");
        foreach $f(@params) {
                ($name,$val)=split(/=/,$f,2);
                next if (lc($name) ne "href");
                $val =~ s/^"(.*)"$/$1/;
                push @linx,$val;
                }
        }

perl socket

#!/usr/bin/perl -w
use strict;

use IO::Socket;

my $host = "www.naver.com";
my $header = "GET / HTTP/1.1 
Host:www.naver.com\n\n";

my $remote = IO::Socket::INET->new( Proto     => "tcp",
                                 PeerAddr  => $host,
                                 PeerPort  => "http(80)",
                                );
unless ($remote) { die "cannot connect to http daemon on $host" }
$remote->autoflush(1);
print "--------- HTTP REQUEST to $host --------\n";
print $header;
print "--------- HTTP RESPONSE from $host --------\n";
print $remote $header;

while ( <$remote> ) { print }
close $remote;