자바 NULL 비교시
자바에서는 비교문자.equals("")시 null을 비교 못하는 경우가 발생한다.
그래서 null값을 확인하고 싶다면 !"".equals(비교문자)를 하는게 좋다.
[사용법] 1. 비교문자 != null 2. !"".equals(비교문자) 3. 비교문자.length() != 0 [응용] if(비교문자 != null && !"".equals(비교문자) && 비교문자.length() != 0){ // 수행기능 } |
자바 NULL 비교시
자바에서는 비교문자.equals("")시 null을 비교 못하는 경우가 발생한다.
그래서 null값을 확인하고 싶다면 !"".equals(비교문자)를 하는게 좋다.
[사용법] 1. 비교문자 != null 2. !"".equals(비교문자) 3. 비교문자.length() != 0 [응용] if(비교문자 != null && !"".equals(비교문자) && 비교문자.length() != 0){ // 수행기능 } |
[에러의 종류]
런타임 에러
실행시에 발생하는 에러.
대부분 프로그래밍시의 설계미숙으로 일어나며, 이 외에 기계적 결함 등으로 일어나기도 한다. 설계 실수로 인한 오류인 경우 대표적으로 무한 루프(반복문 안의 조건문의 실수로 인해 반복문을 빠져 나가지 못함) 또는 xx/0 등이 있다.
컴파일타임 에러
컴파일시 발생하는 에러.
대부분이 문법적인 오류. 이 경우 컴파일이 되지 않고 Warning이나 Error 문구가 상태창에 뜨게 된다.
문법 오류와 의미적 오류 등이 있으며, 문장을 끝내는 세미콜론(;)이나 조건문이나 반복문 등의 형식이 맞지 않아서 발생하는 Syntax Error(신택스 에러), 데이터 타입 에러, 함수 선언 에러 등 여러 가지 에러가 있다.
논리 에러
논리 오류로 인해 발생하는 에러.
프로그램 실행은 되지만 프로그래머가 의도하지 않은 결과가 나오는 경우이다.
주로 알고리즘 계산 미스, 복잡한 반복문을 확실하게 설계해놓지 않고 쓰는 경우 발생한다.
[에러의 예시]
1. 오류 코드로 보는 오류 유형
error C2228: Left of ‘.identifier’ must have class/struct/union type |
- 원인
class나 struct, union으로 선언한 변수를 사용하는 경우 ‘.identifier’ 부분이 class, struct union에서 정의한 변수명이 아닌 경우, 혹은 포인터를 사용하면서 ‘->’가 아니라 ‘.’으로 사용한 경우 발생
- 해결법
class, struct, union에서 선언한 변수명과 맞는지 체크하고 포인터 사용하는 경우 ‘.’가 아닌 ‘->’로 접근
error C2143: syntax error : missing ‘;’ before ‘if’ |
- 원인
if문 발생 이전에 ‘;’이 빠진 경우에 발생
- 해결법
명령어가 끝나는 곳에 ‘;’을 붙여준다.
error C2065: ‘.identifier’ : undeclared identifier |
- 원인
.identifier가 선언되지 않고 사용되는 경우에 발생
- 해결법
.identifier 부분 스펠링 확인, 대소문자 확인, 헤더파일이 정확히 include되었는지 확인
error C2106: ‘=’ left operand must be 1-value |
- a=b의 경우 a쪽에 b의 값을 넣을 수 없는 경우에 발생
error LNK2001: unresolved external symbol _main error LNK1120: 1 unresolved externals |
- main 부분을 찾을 수 없는 경우 발생
error C1010: unexpected end of file while looking for precompiled header directive |
- 원인
비주얼C에서 precompiled header를 ‘*.c’ 혹은 ‘*.cpp’파일에 include하지 않은 경우 발생
- 해결법
소스파일에 #include “stdafx.h” 추가
Project-setting0c/c++ tab Project Option text bok에서 /Yu“stdafx.h”부분을 찾아 삭제
error C2143: syntax error : missing ‘;’ before ‘}’ error C1004: unexpected end of file found |
- 원인
{ 와 } 쌍이 맞지 않는 경우 발생
C2143의 경우 } 의 개수가 { 의 개수보다 많은 경우
C1004 에러의 경우 { 의 개수가 } 의 개수보다 많은 경우
- 해결법
{ 와 } 의 개수를 맞게 조정
error C2146: syntax error: missing ‘;’ before identifier ‘printf’ |
- 원인
printf 앞에 세미콜론(;)이 빠짐
- 해결법
세미콜론(;)이 빠진 곳에 세미콜론(;)을 추가
2. 오류 문구로 보는 오류 유형
2-1. 호출 / 선언시
warning C4013: ‘printf’ undefined; assuming extern returning int |
- printf 문을 호출하기 위한 #include<stdio.h>를 선언하지 않음
‘a’ : undeclared identifier |
- 변수 a가 선언되지 않았다. 즉 선언(int, float 등)에 변수가 없음
Declaration is not allowed here |
- while, for, do, if, switch 등의 제어문에는 선언문이 올 수 없다.
Invalid Indirection |
- 간접 연산자(*)는 void pointer 선언이 필요 없음
ex)
int main (void)
{
void *p;
*p = 10; // Invalid Indirection
return 0;
}
Multiple declaration for ‘identifier’ |
- identifier(변수나 함수 등)가 한번 이상 또는 중복 선언되었다.
ex)
int a;
float a;
2-2. 빠뜨림
syntax error : missing ‘)’ before ‘;’ |
- 세미콜론 앞에 ‘)’ 가 빠짐
( expected ) expected , expected < expected { expected } expected |
- (, ), “, ”, <, {, }, :, ; 등이 빠졌음
Declaration syntax error |
- 원인
프로그램 선언부에서 symbol이 빠졌거나 추가가 필요하다는 의미
- 해결법
현재의 라인이나 그 이전의 라인에서 세미콜론(;)이나 괄호({,}) 등을 검사해야 한다.
Undefined symbol ‘identifier’ |
- 사용된 변수 등이 선언부에 빠짐
- 철자상의 오류
Case statement missing : |
- case 문은 다음에 “:”이 빠졌다.
Declaration missing ; |
- struct나 union 선언문에는 반드시 끝에 세미콜론(;)이 나와야 한다.
Declaration terminated incorrectly |
- 함수에서 세미콜론 등이 잘못 위치하여 프로그램에 오류가 발생하여 종료
Declaration was expected |
- 필요한 부호가 빠졌다는 의미.
- 콤마(,), 세미콜론(;), 괄호((,),{,}) 등이 빠짐
Unable to open include file ‘filename’ |
- 컴파일러가 명명한 파일 이름을 찾을 수 없을 때
- 파일이 존재하지 않거나 경로가 올바르지 않은 경우
Undefined label ‘identifier’ |
- goto 문과 상응하는 label의 정의가 없음
Compound statement missing } |
- 중괄호 ({, })의 불일치
Array bounds missing ] OR Delete array size missing ] OR Operator [] missing ] OR Subscripting missing ] |
- “]”가 빠졌다. “[”가 연산자로 선언되었다.
2-3. 문법 구조 오류
Cannot case from ‘type1’ to ‘type2’ |
- type 1과 type 2가 서로 일치 하지 않은 경우
- 포인터는 정수형과 실수형으로 cast 할수 있지만 구조체나 배열은 어느 것으로도 cast가 불가능
Misplaced break |
- break 문은 switch 문이나 루프 안에서만 사용
Misplaced countinue |
- continue 문은 루프 안에서만 사용 가능하다.
Ambiguity between ‘function1’ and ‘function2’ Address of overloaded function ‘function’ does’t match ‘type’ |
- 함수 사이의 변수가 일치하지 않는다.
Array must have at least one element |
- 배열은 하나 이상의 요소가 함께 선언되어야 한다.
Cannot overload ‘main’ |
- main이 한번 이상 쓰였다.
Undefined symbol ‘identifier’ |
- identifier가 선언되지 않았다.
Abnormal program termination |
- 주로 메모리 부족으로 인한 오류
Divide error Floating point error: Divide by 0 |
- 0으로 나누었을 때 발생
제2장 C언어의 기본 구조와 표준 입출력 (0) | 2015.10.29 |
---|---|
제1장 C언어의 소개와 프로그램 작성 방법 (0) | 2015.10.28 |
IP 주소로 PC에 해당 포트가 오픈되어 있는지 확인
using System;
using System.Text;
using System.Net.Sockets;
using System.Net.NetworkInformation;
using System.Net;
public class CheckPort
{
public static void Main(string[] args)
{
try
{
if (args.Length < 1)
{
Console.WriteLine("Usage : CheckPort.exe [IP] [Port]");
Console.WriteLine(" CheckPort.exe 192.168.0.1 80");
return;
}
string ip = args[0];
int port = Convert.ToInt32(args[1]);
if (PingTest(ip))
{
Console.WriteLine("{0} PING OK", ip);
if (ConnectTest(ip, port))
{
Console.WriteLine("{0}:{1} is open.", ip, port);
}
else
{
Console.WriteLine("{0}:{1} is closed.", ip, port);
}
}
else
{
Console.WriteLine("{0} PING NG", ip);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
private static bool PingTest(string ip)
{
bool result = false;
try
{
Ping pp = new Ping();
PingOptions po = new PingOptions();
po.DontFragment = true;
byte[] buf = Encoding.ASCII.GetBytes("aaaaaaaaaaaaaaaaaaaa");
PingReply reply = pp.Send(
IPAddress.Parse(ip),
10, buf, po
);
if (reply.Status == IPStatus.Success)
{
result= true;
}
else
{
result = false;
}
return result;
}
catch
{
throw;
}
}
private static bool ConnectTest(string ip, int port)
{
bool result = false;
Socket socket = null;
try
{
socket = new Socket(
AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp
);
socket.SetSocketOption(
SocketOptionLevel.Socket,
SocketOptionName.DontLinger,
false
);
IAsyncResult ret = socket.BeginConnect(ip, port, null, null);
result = ret.AsyncWaitHandle.WaitOne(100, true);
}
catch { }
finally
{
if (socket != null)
{
socket.Close();
}
}
return result;
}
}
netstat 구현
using System;
using System.Net;
using System.Net.Networkinformation
namespace MyNetstat
{
class Program
{
static void Main(string[] args)
{
IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();
IPEndPoint[] endPoints = ipProperties.GetActiveTcpListeners();
TcpConnectioninformation[] tcpConnections = ipProperties.GetActiveTcpConnections();
foreach(TcpConnectioninformation info in tcpConnections)
{
Console.WriteLine("Local: " + info.LocalEndPoint.Address.ToString()
+ ":" + info.LocalEndPoint.Port.ToString()
+ "\nRemote: " + info.RemoteEndPoint.Address.ToString()
+ ":" + info.RemoteEndPoint.Port.ToString()
+ "\nState : " + info.State.ToString() + "\n\n");
}
Console.ReadLine();
}
}
}
프로세스 정보 얻어 오는 방법 (0) | 2015.11.04 |
---|
실행중인 프로세스 이름 받아 오기 : Process[] process = Process.GetProcessByName
실행중인 프로세스 종료 : process[0].KILL()
밑에 표는 도대체 뭔지 모르겠지만 일단 Keep....
ProcessStartInfo CMD = new ProcessStartInfo(); Process pro = new Process(); CMD.FileName = @"cmd"; // 실행할 응용프로그램의 경로를 설정 CMD.Window Style = ProcessWindowStyle.Hidden; // 실행할 프로그램을 숨긴다???? CMD.CreateNoWindow == true; // 실행할 프로그램의 창을 생성하지 않는다??????? CMD.UseShellExecute = false; // 프로세스를 시작할 때 운영체제 셸을 사용할지 여부를 나타내는 값을 가져오거나 설정한다. // 라고 MSDN이 그러는데 뭔소린진 잘 모르겠다....????? CMD.RedirectStandardOutput = true; // CMD 창의 내용을 가져오기 CMD.RedirectStandardInput = true; // CMD 창의 데이터를 보내기 CMD.RedirectStandardError = true; // 오류내용 가져오기 pro.EnableRaisingEvents = false; // 프로세스가 종료될 때 exited 이벤트를 발생시키지 않는다. pro.StartInfo = CMD; // ProcessStartInfo의 인스턴트인 CMD를 넣어줌 pro.Start(); // 시작 pro.StandardInput.Write(@"Hi! I'm LOGIC!" + Environment.NewLine); //마무리로 Environment.NewLine이 꼭 필요하다고 한다. pro.StandardInput.Close(); // 닫음 textBox1.Text = process.StandardOutput.ReadToEnd(); // 해당 프로세스의 내용을 스트림으로 끝까지 읽어온다. pro.WaitForExit(); pro.Close(); // 프로세스 종료 // textbox1에 CMD의 내용을 출력한다. |
이건 도움이 되겠다!!(표에 안들어갈까...ㅠㅠ)
-----------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace ProcessInfoWrite
{
class Program
{
static void Main(string[] args)
{
try
{
Process[] allProc = Process.GetProcesses(); //시스템의 모든 프로세스 정보 출력
int i = 1;
Console.WriteLine("****** 모든 프로세스 정보 ******");
Console.WriteLine("현재 실행중은 모든 프로세스 수 : {0}", allProc.Length);
foreach (Process p in allProc)
{
Console.WriteLine("***** {0}번째 프로세스 ******", i++);
WriteProcessInfo(p);
Console.WriteLine();
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
private static void WriteProcessInfo(Process processInfo)
{
Console.WriteLine("Process : {0}", processInfo.ProcessName);
Console.WriteLine("시작시간 : {0}", processInfo.StartTime);
Console.WriteLine("프로세스 PID : {0}", processInfo.Id);
Console.WriteLine("메모리 : {0}", processInfo.VirtualMemorySize);
}
}
}
특수 문자 : 특수한 역할을 하는 문자
특수문자 | 설명 |
\a | 경고음 소리 발생 |
\b | 백스페이스(Backspace) |
\f | 폼 피드(Form Feed) |
\n | 개행(New Line) |
\r | 캐리지 지턴(Carriage Return) |
\t | 수평 탭 |
\v | 수직 탭 |
\\ | 역슬래시(\) |
\' | 작은따옴표 |
\" | 큰따옴표 |
서식문자 : 서식화된 문자
printf() 함수 : Print와 Formatted에서 print에 f를 추가하여 만든 함수
Formatted : '서식화된'의 의미
출력 서식 문자 예시
출력 서식 문자(서식화된 출력 문자)
서식문자 |
출력형태 |
%d, %i |
10진수 정수(양수와 음수 모두 표현 가능) |
%x, %o |
16진수 정수, 8진수 정수(양수만 표현 가능) |
%f, %lf |
10진수 실수(양수와 음수 모두 표현 가능) |
%c |
한 개의 문자 |
%s |
문자열 |
%u |
10진수 정수(양수만 표현 가능) |
%e |
e 표기법에 의한 실수 |
%E |
E 표기법에 의한 실수 |
%g |
소수점 이하 자리 수에 따라 %f, %e 둘 중 하나를 선택 |
%G |
소수점 이하 자리 수에 따라 %f, %E 둘 중 하나를 선택 |
%% |
% 기호 출력 |
키보드로 데이터 입력 받기(scanf() 함수)
printf() 함수와 scanf() 함수
printf() 함수 | scanf() 함수 |
모니터에 데이터를 출력하는 함수 | 키보드로 데이터를 입력하는 함수 |
stdio.h 헤더 파일이 필요 | |
Print와 Formatted에서 print와 f를 추가해서 만든 함수(출력 서식 필요) | Scan과 Formatted에서 scan과 f를 추가하여 만든 함수(입력 서식 필요) |
scanf() 함수의 기본 구조
입력 서식 문자
변수(데이터를 저장하는 임시 공간)
키보드로부터 데이터를 입력 서식 문자(%d) 형식으로 입력을 받는다.
입력받은 데이터를 변수 a의 주소값(&a)에 저장한다.
C언어 오류 유형 (0) | 2015.11.07 |
---|---|
제1장 C언어의 소개와 프로그램 작성 방법 (0) | 2015.10.28 |
C언어 오류 유형 (0) | 2015.11.07 |
---|---|
제2장 C언어의 기본 구조와 표준 입출력 (0) | 2015.10.29 |