c언어 동적할당, fgets 질문합니다.

dltmdgns의 이미지

안녕하세요?
c언어 동적할당 질문드립니다.

일단 저는 파일에서 읽어오는것을 연습하고 있습니다.
책에 연습문제인데요 답은 못구했구요.
문제는 파일을 읽어와서 특정 문자열이 포함되는 줄을 구하는 문제입니다.

buffer라는 배열을 만들어서 버퍼로 쓰고 있고요, fgets()로 파일에서 한줄씩 읽어 옵니다.
하지만 한줄씩 읽을때 버퍼로 사용하는 배열의 크기보다 한줄이 길어지면 인식하지 못해
해결중입니다.
그래서 일단 fgets으로 읽었을때 한줄이 끝난것과 아닌것을 구분하는 if-else로 만들었습니다.
아래 31번줄과 38번 줄입니다.

제가 프로그램한 한줄이 끝나지 않았을경우에서 동적할당으로 계속 더해주면 될꺼 같은데
어렵네요..
일단 저는 *pTemp라고 포인터 변수를 선언해서 입력된 버퍼 크기만큼 동적할당을 해봤는데 한줄이 끝나지 않았을 경우 포인터 연산하는 과정을 모르겠습니다.
조언 부탁드립니다..

/* 8. 파일에서 특정한 문자열을 검색하여 검색된 줄 번호와 그 내용을 출력하는 프로그램을 작성하시오. */
#include
#include
#include

#define MAX_READ_SIZE 10

void searchString(char *pArr, int pArrLength, int LineCounter);

int main(void)
{
FILE *fp;
int LineCounter = 0;

char buffer[10];
char *pBuffer = buffer;

char *pTemp = NULL;
char *pTemp2 = NULL;

fp = fopen("srcfile.txt", "r");
if(fp==NULL)
{
printf("can't open file\n");
return 0;
}

fgets(buffer, MAX_READ_SIZE, fp); //200

while(!feof(fp))
{
if(buffer[strlen(buffer)-1]=='\n') //이제 한줄을 모두 읽었으니 검색함수 호출
{
//printf("\n미만\n");
LineCounter++;
searchString(buffer, (int)strlen(buffer), LineCounter);
}

else //최대 읽는 크기를 초과할때, 아직 한줄이 끝나지 않음.
{
//printf("\n초과\n");
pTemp = (char *)malloc((int)strlen(buffer) * sizeof(char));
strcpy(pTemp, buffer);

}

printf("****************\n");
fgets(pBuffer, MAX_READ_SIZE, fp);
}

free(pTemp2);
free(pTemp);
fclose(fp);

return 0;
}

void searchString(char *pArr, int pArrLength, int LineCounter)
{
if(strstr(pArr, "my"))
{
printf("%d번쨰줄 my 포함: %s\n", LineCounter, pArr);
} else {
printf("%d번쨰줄 my 미포함: %s\n", LineCounter, pArr);
}
}

qiiiiiiiip의 이미지

realloc으로 메모리 키우면서
끝에다가 계속 읽어나가면 됩니다..

ymir의 이미지

일단 buffer 를 4k 정도로 크게 잡으시면, 별로 고민할 필요가 없을 겁니다.

그래도.. 만약 한 line 이 4k 보다 더 크다면...?? (\n 으로 끝나지 않았다면..)

일단 읽어들인 상태에서 문자열 검색 한번 하시고..
buffer 의 뒤에서부터 (검색할 문자열 길이 - 1) 만큼을 buffer 맨 앞으로 move 하고..
그 뒤에서부터 이어서 다시 파일을 읽어 들인 후, 계속 문자열 검색을 하면..
malloc 같은거 고민할 필요 없이 buffer 하나로 어케 될 것 같네요..

char buffer[BUFSIZ];
int line_num = 1;
size_t left = 0;
 
while (fgets(&buffer[left], sizeof(buffer) - left, fp))
{
	search string from buffer
 
	if (string not found in buffer)	
	{
		if (buffer[strlen(buffer) - 1] == '\n')
		{
			line_num++;		// next line number
			left = 0;
		}
		else
		{
			left = search_string_length - 1;
			memmove(&buffer[0], &buffer[strlen(buffer) - left], left);
		}
	}
}

되면 한다! / feel no sorrow, feel no pain, feel no hurt, there's nothing gained.. only love will then remain.. 『 Mizz 』

댓글 달기

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
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.