C언어 수업정리/5월 수업정리

5월 6일 파일 입출력

송시혁 2013. 5. 6. 15:58


#include <stdio.h>
int main()
{
  


  printf("1. hello\n");
  fprintf(stdout, "1. hello\n");

  fclose(stdout);  
  
  printf("2. hello\n");
  fprintf(stdout, "2. hello\n");





  return 0;
}

fclose에 의해 fclose 밑에 printf문과 fprintf문은 
실행되지 않는다.




#include <stdio.h>
#include <process.h>
#include <stdlib.h>
#define LENGTH 10
int main(int argc, char *argv[])
{
  int i;
  FILE *fp;
  char ch;
  char string[LENGTH +1];
  i=0;
  if(argc !=2)
  {
    printf("Wrong in command line");
    exit(-1);
  }
  //실행시 조건이다

rb는 2진바이너리로 읽는것이다.
  if((fp= fopen (argv[1], "rb")) == NULL)
  {
    printf("Can't open file %s.", argv[1]);
    exit(-1);
  }


  while((ch = fgetc(fp)) != EOF)
  {
    printf("%3x", ch);
    if(ch > 31)
    {
      *(string + i)=ch;
      i= i+1;
    }
    else
    {
      *(string + i)= '.';
      i=i+1;
    }
    
    if(i>=LENGTH)
    {
      *(string +i) = '\0';
      printf("        %s\n", string);
      i=0;
    }
  }
    
  fclose(fp);
    
  
  return 0;
}
반복문에서 아스키코드로 제어문자가 31이므로
31보다 큰 수를 문자열에 ch값을 넣는다.
그밖에 '.'을 찍는다.
그리고 밑에 if문에 널문자를 넣어서 문자열로 만든다.
printf문에서는 공백을 두어서 오른쪽에 출력한다.
그리고 i를 초기화 하여 10줄까지만 출력하고 
밑에 출력한다.