using System; using System.IO; class WriteTextFile { static void Main() { // These examples assume a "C:\Users\Public\TestFolder" folder on your machine. // You can modify the path if necessary. // Example #1: Write an array of strings to a file. // Create a string array that consists of three lines. string[] lines = { "First line", "Second line", "Third line" }; System.IO.File.WriteAllLines(@"C:\price\WriteLines.txt", lines); // Example #2: Write one string to a text file. string text = "A class is the most powerful data type in C#. Like structures, " + "a class defines the data and behavior of the data type. "; System.IO.File.WriteAllText(@"C:\price\WriteText.txt", text); // Example #3: Write only some strings in an array to a file. using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\price\WriteLines2.txt")) { foreach (string line in lines) { if (line.Contains("Second") == false) { file.WriteLine(line); } } } // Example #4: Append new text to an existing file using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\price\WriteLines2.txt", true)) { file.WriteLine("Fourth line"); } } } /* Output (to WriteLines.txt): First line Second line Third line Output (to WriteText.txt): A class is the most powerful data type in C#. Like structures, a class defines the data and behavior of the data type. Output to WriteLines2.txt after Example #3: First line Third line Output to WriteLines2.txt after Example #4: First line Third line Fourth line */
Tag Archives: 파일입출력
파일 입출력 Random Access
#include <stdio.h>
int fseek(FILE * stream, long offset, int wherefrom)
fseek(stream, 2, SEEK_CUR) // 이런 형식으로 입력
wherefrom의 전달인자
SEEK_SET 이라면 파일의 맨 앞으로 이동한다.
SEEK_CUR 이라면 이동하지 않는다. // SSEK_CUR은 현재 위치를 기준으로 이동한다.
SEEK_END 이라면 파일의 끝으로 이동한다.
long offset 위치의 숫자를 +-숫자로 지정해서 앞뒤로 이동
SEEK_SET(SEEK_END)을 전달하면 현재의 파일 위치 지시자의 위치에 상관없이 파일의 맨 앞(뒤)을 기준으로 fseek함수의 두 번째 인자의 크기만큼 이동한다.
SEEK_CUR
파일 입출력 함수
파일 입 출력 함수들
키보드/모니터 | 선택(키보드/모니터,파일) | |
문자출력 | int purchar(int c) | int fputc(int c, FILE* stream) |
문자입력 | int getchar(void) | int fgetc(FILE* stream) |
문자열 출력 | int puts(const char* s) | int fputs(const char* s, FILE* stream) |
문자열 입력 | char* gets(char* s) | char* fgets(char* s,int n, FILE* stream) |
형식 지정 출력 | int printf(const* format, ...) | int fprintf(FILE* stream, cnost char* format,...) |
형식 지정 입력 | int scanf(const char* format, ...) | int fscanf(FILE*stream, const char* format,...) |
puts("Dont' worry!"); // puts는 모니터상으로 출력
fputs("dont'w worry!\n", stdout); // stdout 스트림을 활용 모니터에 출력
fputs("dont worry!\n", file); // file 스트림을 활용.. fopen을 통해 개방된 파일에 저장
char buf[30];
fputs("데이터 입력: ", stdout);
fgets(buf, sizeof(buf), stdin); //buf 배열에 stdin을 통해 문자열을 입력 후 ENTER
puts(buf); //buf에 저장된 문자열을 출력
fgets(buf,sizeof(buf), file); // buf배열에 file의 문자열을 buf의 크기 한도 내에서 저장
puts(buf); // buf를 출력
파일 입 출력 함수와 FILE 구조체 변수----------------------------
파일위치 지시자...File Position Indicator
fgetc, fgets등을 여러번 호출하면 이전에 호출했던 위치에서 이어서 호출이 된다.
이러한 일이 가능한 것은 파일을 어디까지 읽었는지 어디까지 섰는지 그 위치를 기억하고 있다는 뜻.
= 파일을 개방하는 경우 이에 대한 FILE 구조체 변수의 포인터가 리턴되고, 그 포인터가 가리키는 구조체 변수 내에는 '파일 위치 지시자'에 해당하는 변수가 존재한다. 이 변수는 파일 내의 위치 정보를 지니고 있으며, 이 변수의 값은 파일에서부터 데이터를 읽거나 쓰는 경우 변경된다.
--------------파일의 끝에 도달한 경우 리턴------------
fgetc --> EOF(-1)을 리턴
fgets --> NULL포인터 (0)
fscanf --> EOF(-1)
----------feof 파일의 끝을 검사하는 함수---------
#include <stdio.h>
int feof(FilE*stream)
~~~~~~~~~~~~~~
file=fopen("Test.txt","rb"); //읽기전용 파일 개방
if(file==NULL){
printf("file open error!\n");
return 1;
}
while(1)
{
ch=fgetc(file);
if(feof(file)!=0) //feof함수를 활용해 파일을 끝을 검사하고 break로 종료
break;
printf("data : %c \n", ch);
}
//여기서 파일을 종결하면 됨
state=fclose(file);
if(state!=0){
printf("file close error!\n");
return 1;
}
return 0;
파일입출력 - 파일의 개방 open 종결 close
fopen함수 - 파일 개방
#include <stdio.h>
FILE* fopen (const char * filename, const char * mode)
성공 시 해당 파일의 파일포인터, 실패시 NULL 포인터 리턴
fclose함수 - 파일 종결
#include <stdio.h>
int fclose (FILE * stream)
종료가 오류 없이 제대로 이뤄지면 0을 리턴
사용 예
#include <stdio.h>
int main(void)
{
int state;
FILE*file=fopen("c:\\work\\test.txt", "rt"); //파일 개방
if(file==NULL){
printf("file open error\n");
return 1;
}
state=fclose(file); //파일의 종결
if(state!=0){
printf("file close error!\n");
return 1;
}
return 0;
}
파일 접근 모드
r - 읽기전용
w - 쓰기전용, 파일이 없으면 새로 생성, 파일이 있으면 기존파일을 지우고 생성
a - 파일의 끝에서 내용추가 전용
r+ -파일을 읽고 쓰기, 파일이 존재하지 않으면 새로운 파일 생성, 파일이 존재하면 데이터를 덮어쓰기
w+ - 파일을 읽고 쓰기, 파일이 존재하지 않으면 새로운 파일 생성, 파일이 존재하면 기존파일을 지우고 생성
a+ - 파일을 읽고 쓰기, 파일이 존재하지 않으면 새로운 파일 생성, 파일이 존재하면 끝에서부터 데이터 추가
데이터 입출력 모드 541p
t - 텍스트 모드
b - 바이너리 모드(2진 모드)