텍스트 파일에 쓰고 출력을 하려고 합니다

PineTree514의 이미지

유저로부터 이름을 입력받고 name.txt파일을 만들어 생성을 한 다음

그 내용을 다시 화면에 출력하려고 합니다.

이틀째 계속 이것 저것 고쳐가며 하고 있는데 잘 안되네요.

#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#define MAX_SIZE 500
 
int main(void)
{
   int i, fd;
   char nameBuf[MAX_SIZE];
 
   fd=open("name.txt", O_RDWR|O_CREAT, 0744);
   if(fd<0)
   {
        perror("An error occured while opening the file");
        exit(1);
   }
 
   while(1)
   {
        puts("Enter name(end to quit) : ");
        read(0, nameBuf, sizeof(nameBuf));
 
        if( !strncmp(nameBuf, "end", 3) )
        {
                printf("end input\n");
                break;
        }
        write(fd, nameBuf, 7);
   }
 
 
   printf("for loop begins...\n");
   for(i=0; i<3; i++)
   {
        fprintf(stdout, nameBuf);
    }
 
   puts("Operation completed...");
 
   close(fd);
 
   return 0;
}
익명 사용자의 이미지

여러가지방법이있겠지만

첫번째로는 쓴 내용에 대한 수정이 더 이상 필요없다면 씀과동시에 출력하는방법이있겠구요,

두번째로는 기존에 사용하신 파일포인터를 맨앞으로 당겨서 읽어가며 출력하는 방법이있습니다.

세번째로는 문자열을 배열구조로 만들어서 저장한다면 문제가 해결되겠군요.

기존에 작성하신 소스의 문제는 write를 함과동시에 다음루프에서 새로운 입력값으로 초기화가 되어 루프를 빠져나오면 기존에 갖고있던 정보가 사라진다는 점이 문제가됩니다.

racer79의 이미지

/*
linux gcc로 컴파일 및 테스트
파일에 저장되어 있는 DATA를 화면에 뿌리고 싶으시면, 아래 #define READ_FILE 부분의 주석을 해제
입력받은 DATA만 뿌리고 싶으면, 현재처럼 ...
*/
#include
#include
#include
#include
#include

/* 파일에 저장한 것을 읽을 지 말지 define */
//#define READ_FILE

#define MAX_SIZE 500

int main(void)
{
#ifdef READ_FILE
int n=0, fd;
#else
int i=0, n=0, fd;
#endif
char nameBuf[MAX_SIZE];

/* 실행 시, 기존에 파일에 저장되어 있는 DATA 삭제 */
fd=open("name.txt", O_RDWR|O_CREAT|O_TRUNC, 0744);
if(fd<0)
{
perror("An error occured while opening the file");
exit(1);
}

while(1)
{
#ifdef READ_FILE
puts("Enter name(end to quit) : ");
n = read(0, nameBuf, sizeof(nameBuf));
nameBuf[n] = 0;
if (!strncmp(nameBuf, "end", 3)) {
printf("end input\n");
break;
}

write(fd, nameBuf, n);
#else
puts("Enter name(end to quit) : ");
/* 남은 버퍼보다 더 저장하는 것을 방지하기 위하여, sizeof(nameBuf) - i */
n = read(0, &nameBuf[i], sizeof(nameBuf) - i);

/* 남은 버퍼가 없으면 입력 종료 */
if( (i + n >= sizeof(nameBuf)) || !strncmp(&nameBuf[i], "end", 3) )
{
nameBuf[i] = 0;
printf("end input\n");
break;
}
write(fd, &nameBuf[i], n);
/* 입력 받은 DATA 만큼 새로 입력 받을 Buf 위치를 수정 */
i += n;
/* 제일 끝에 0 추가 ( 출력시 쓰레기값 출력 방지 ) */
nameBuf[i] = 0;
#endif
}

#ifdef READ_FILE
/* 파일 포인터를 파일의 제일 처음으로 이동 */
lseek(fd, 0, SEEK_SET);
while (1)
{
/* 파일로부터 DATA를 읽어옴 */
n = read(fd, nameBuf, sizeof(nameBuf));
if (n <= 0)
break;
/* 제일 끝에 0 추가 ( 출력시 쓰레기값 출력 방지 ) */
nameBuf[n] = 0;
printf("%s", nameBuf);
}
#else
/* 버퍼에 저장된 이름값들을 출력 */
fprintf(stdout, nameBuf);
#endif
puts("Operation completed...");
close(fd);

return 0;
}

racer79의 이미지

include가 다 지워졌네요
stdio.h
fcntl.h
stdlib.h
unistd.h
string.h

입니다.

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.