예 :C의 텍스트 파일에서 특정 줄을 어떻게 삭제합니까?
조지 50 40
라임 30 20
카렌 10~60
do {
printf("\nInput player name:[1..10] ");
fgets(name,10,stdin);
}
입력 이름 : 라임
그러면 텍스트 파일이 될 것이다
조지 (50) (40)
카렌 (10) (60)
예 :C의 텍스트 파일에서 특정 줄을 어떻게 삭제합니까?
조지 50 40
라임 30 20
카렌 10~60
do {
printf("\nInput player name:[1..10] ");
fgets(name,10,stdin);
}
입력 이름 : 라임
그러면 텍스트 파일이 될 것이다
조지 (50) (40)
카렌 (10) (60)
이 시도 :
/* C Program Delete a specific Line from a Text File
*/
#include <stdio.h>
int main()
{
FILE *fileptr1, *fileptr2;
char filename[40];
char ch;
int delete_line, temp = 1;
printf("Enter file name: ");
scanf("%s", filename);
//open file in read mode
fileptr1 = fopen(filename, "r");
ch = getc(fileptr1);
while (ch != EOF)
{
printf("%c", ch);
ch = getc(fileptr1);
}
//rewind
rewind(fileptr1);
printf(" \n Enter line number of the line to be deleted:");
scanf("%d", &delete_line);
//open new file in write mode
fileptr2 = fopen("replica.c", "w");
ch = 'A';
while (ch != EOF)
{
ch = getc(fileptr1);
//except the line to be deleted
if (temp != delete_line)
{
//copy all lines in file replica.c
putc(ch, fileptr2);
}
if (ch == '\n')
{
temp++;
}
}
fclose(fileptr1);
fclose(fileptr2);
remove(filename);
//rename the file replica.c to original name
rename("replica.c", filename);
printf("\n The contents of file after being modified are as follows:\n");
fileptr1 = fopen(filename, "r");
ch = getc(fileptr1);
while (ch != EOF)
{
printf("%c", ch);
ch = getc(fileptr1);
}
fclose(fileptr1);
return 0;
}
참조 - http://www.sanfoundry.com/c-program-delete-line-text-file/
당신이 줄을 삭제 할 수있는 몇 가지 방법, 하나의 간단한 방법은 두 가지를 열 수 있습니다 파일, 1 개 및 1 개
한 줄씩 복사하고 완료 후 줄을 건너 뛰고 이전 파일을 삭제하고 새 파일의 이름을 이전 이름으로 바꿉니다.
fopen()
fgets()
fputs()
rename()
unlink()
편집 : 위의 솔루션은 작은 파일로 잘 작동 것이지만, 주석 등에 의해 그렇게 여기에 대용량 파일에 적합하지 않은 대안 솔루션 전체 파일을 읽습니다 (GCC C99가)에서 발견 온다 name은 버퍼에서 그 라인 다음의 라인을 앞으로 이동시킨다.
#include <stdio.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <stdbool.h>
static size_t deleteLine(char*, size_t, const char*);
int main(int argc, char* argv[])
{
char file[] = "yourfile.txt";
if (--argc)
{
struct stat st;
if (stat(file, &st) != -1)
{
// open the file in binary format
FILE* fp = fopen(file, "rb");
if (fp != NULL)
{
// allocate memory to hold file
char* buffer = malloc(st.st_size);
// read the file into a buffer
if (fread(buffer, 1, st.st_size, fp) == st.st_size)
{
fclose(fp);
size_t newSize = deleteLine(buffer, st.st_size, argv[1]);
fp = fopen(file, "wb");
if (fp != NULL)
{
fwrite(buffer, 1, newSize, fp);
fclose(fp);
}
else
{
perror(file);
}
}
free(buffer);
}
else
{
perror(file);
}
}
else
{
printf("did not find %s", file);
}
}
return 0;
}
static size_t deleteLine(char* buffer, size_t size, const char* playerName)
{
// file format assumed to be as specified in the question i.e. name{space}somevalue{space}someothervalue\n
// find playerName
char* p = buffer;
bool done = false;
size_t len = strlen(playerName);
size_t newSize = 0;
do
{
char* q = strchr(p, *playerName); // look for first letter in playerName
if (q != NULL)
{
if (strncmp(q, playerName, len) == 0) // found name?
{
size_t lineSize = 1; // include \n already in line size
// count number of characters the line has.
for (char* line = q; *line != '\n'; ++line)
{
++lineSize;
}
// calculate length left after line by subtracting offsets
size_t restSize = (size_t)((buffer + size) - (q + lineSize));
// move block with next line forward
memmove(q, q + lineSize, restSize);
// calculate new size
newSize = size - lineSize;
done = true;
}
else
{
p = q + 1; // continue search
}
}
else
{
puts("no such name");
done = true;
}
}
while (!done);
return newSize;
}
그리고 수 천 라인의 여러 파일에 내가 그 수행하려는 경우? 아주 좋은 해결책이 아닙니다 ... – Nepho
이 맞습니다. OP 질문에 대한 답이 교정되었으므로 실제 문제가 발생했을 때 10 줄 정도의 파일이있는 학교 과제가 있습니다. –
'main'에서'free (buffer)'할 필요가 없습니까? –
나는 코드에 대한이 C인지 의심 ... : -/ – rjv
** 힌트 : ** 경우() –