그래서 저는 3 개의 명령 줄 인수, 1. 기존 파일의 이름, 2. 새 파일의 이름, 3. 각 줄에서 새 파일로 복사 할 문자 수를 사용하는 프로그램을 작성하려고합니다.
지금까지 내가 가지고있는 것은 다음과 같습니다.
int main(int argc, char *argv[]) {
int size = atoi(argv[3]); // The number of characters to copy
char content[size];
char line[size];
FILE *f1 = fopen(argv[1], "r"); // Read from first file
FILE *f2 = fopen(argv[2], "w"); // Write to second file
if (f1 == NULL || f2 == NULL) {
printf("\nThere was an error reading the file.\n");
exit(1);
}
while (fgets(content, size, f1) != NULL) {
// This is what I had first:
fprintf(f2, "%s", content);
// And when that didn't work, I tried this:
strncpy(line, content, size);
fprintf(f2, "%s", line);
}
fclose(f1);
fclose(f2);
return 0;
}
미리 감사드립니다!
문제는 fgets
작동 방식 입니다. 다음 줄의 끝 이나 최대 size
문자 수 중 먼저 오는 쪽 을 읽도록 설계되었습니다 . 이 읽는 경우 size
개행 문자를 읽기 전에 문자를, 그 반환 size
다음으로 읽어 들여, - 길이 문자열을하지만, 입력 스트림에서 행의 나머지 잎 fgets
호출! 따라서 size
10이면 루프는 10 자 단위로 긴 행을 읽지 만 한 번에 10 자씩 전체 행을 출력합니다.
현재 프로그램의 구조를 유지하려면 트릭을 사용 fgets
하여 전체 줄을 읽고 ( size
가능한 가장 긴 줄보다 긴 값을 사용하여 ) 줄 바꿈이 있으면 제거하고 줄을 다음 줄로 자릅니다. n
문자 (NUL- 종료)를 입력하고 단축 된 줄을 인쇄합니다.
힌트로 충분합니까, 아니면 실제 예제를 원했습니까?
편집 : 좋아, 여기에 하나의 작업 솔루션이 있습니다.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char line[4096];
int main(int argc, char *argv[]) {
int size = atoi(argv[3]); // The number of characters to copy
FILE *f1 = fopen(argv[1], "r"); // Read from first file
FILE *f2 = fopen(argv[2], "w"); // Write to second file
if (f1 == NULL || f2 == NULL) {
printf("\nThere was an error reading the file.\n");
exit(1);
}
// read whole line
// note: if the whole line doesn't fit in 4096 bytes,
// we'll be treating it as multiple 4096-byte lines
while (fgets(line, sizeof(line), f1) != NULL) {
// NUL-terminate at "size" bytes
// (no effect if already less than that)
line[size] = '\0';
// write up to newline or NUL terminator
for (char* p = line; *p && *p != '\n'; ++p) {
putc(*p, f2);
}
putc('\n', f2);
}
fclose(f1);
fclose(f2);
return 0;
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다