C에서 텍스트 파일을 읽고 모든 문자열을 인쇄하는 방법
이름이 지정된 텍스트 파일이 있습니다. test.txt
이 파일을 읽고 내용을 콘솔에 인쇄 할 수있는 C 프로그램을 작성하고 싶습니다 (파일에 ASCII 텍스트 만 포함되어 있다고 가정).
내 문자열 변수의 크기를 얻는 방법을 모르겠습니다. 이렇게 :
char str[999];
FILE * file;
file = fopen( "test.txt" , "r");
if (file) {
while (fscanf(file, "%s", str)!=EOF)
printf("%s",str);
fclose(file);
}
에서 999
반환 된 문자열 fscanf
이 그보다 클 수 있기 때문에 크기 가 작동하지 않습니다 . 어떻게 해결할 수 있습니까?
가장 간단한 방법은 문자를 읽고 읽은 직후에 인쇄하는 것입니다.
int c;
FILE *file;
file = fopen("test.txt", "r");
if (file) {
while ((c = getc(file)) != EOF)
putchar(c);
fclose(file);
}
c
는 음수 int
이기 때문에 위이며 EOF
일반 char
은 unsigned
.
청크 단위로 파일을 읽으려면 동적 메모리 할당없이 다음을 수행 할 수 있습니다.
#define CHUNK 1024 /* read 1024 bytes at a time */
char buf[CHUNK];
FILE *file;
size_t nread;
file = fopen("test.txt", "r");
if (file) {
while ((nread = fread(buf, 1, sizeof buf, file)) > 0)
fwrite(buf, 1, nread, stdout);
if (ferror(file)) {
/* deal with error */
}
fclose(file);
}
위의 두 번째 방법은 기본적으로 동적으로 할당 된 배열로 파일을 읽는 방법입니다.
char *buf = malloc(chunk);
if (buf == NULL) {
/* deal with malloc() failure */
}
/* otherwise do this. Note 'chunk' instead of 'sizeof buf' */
while ((nread = fread(buf, 1, chunk, file)) > 0) {
/* as above */
}
fscanf()
with %s
as 형식 의 방법은 파일의 공백에 대한 정보를 잃어 버리기 때문에 파일을 stdout
.
여기에 청크로 읽는 것에 대한 좋은 답변이 많이 있습니다. 모든 내용을 한 번에 버퍼로 읽어서 인쇄하는 작은 트릭을 보여 드리겠습니다.
더 낫다는 말이 아닙니다. 그렇지 않고 Ricardo가 때로는 나쁠 수 있지만 간단한 경우에는 좋은 해결책이라고 생각합니다.
많은 일이 일어나고 있기 때문에 코멘트를 뿌렸습니다.
#include <stdio.h>
#include <stdlib.h>
char* ReadFile(char *filename)
{
char *buffer = NULL;
int string_size, read_size;
FILE *handler = fopen(filename, "r");
if (handler)
{
// Seek the last byte of the file
fseek(handler, 0, SEEK_END);
// Offset from the first to the last byte, or in other words, filesize
string_size = ftell(handler);
// go back to the start of the file
rewind(handler);
// Allocate a string that can hold it all
buffer = (char*) malloc(sizeof(char) * (string_size + 1) );
// Read it all in one operation
read_size = fread(buffer, sizeof(char), string_size, handler);
// fread doesn't set it so put a \0 in the last position
// and buffer is now officially a string
buffer[string_size] = '\0';
if (string_size != read_size)
{
// Something went wrong, throw away the memory and set
// the buffer to NULL
free(buffer);
buffer = NULL;
}
// Always remember to close the file.
fclose(handler);
}
return buffer;
}
int main()
{
char *string = ReadFile("yourfile.txt");
if (string)
{
puts(string);
free(string);
}
return 0;
}
유용하거나 배울 수 있는지 알려주세요. :)
대신 텍스트 파일이 매우 클 수 있고 많은 메모리가 필요할 수 있으므로 문자를 콘솔에 직접 인쇄하십시오.
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *f;
char c;
f=fopen("test.txt","rt");
while((c=fgetc(f))!=EOF){
printf("%c",c);
}
fclose(f);
return 0;
}
fscanf 대신 "read ()"를 사용하십시오.
ssize_t read(int fildes, void *buf, size_t nbyte);
기술
The read() function shall attempt to read
nbyte
bytes from the file associated with the open file descriptor,fildes
, into the buffer pointed to bybuf
.
Here is an example:
http://cmagical.blogspot.com/2010/01/c-programming-on-unix-implementing-cat.html
Working part from that example:
f=open(argv[1],O_RDONLY);
while ((n=read(f,l,80)) > 0)
write(1,l,n);
An alternate approach is to use getc
/putc
to read/write 1 char at a time. A lot less efficient. A good example: http://www.eskimo.com/~scs/cclass/notes/sx13.html
Two approaches leap to mind.
First, don't use scanf
. Use fgets()
which takes a parameter to specify the buffer size, and which leaves any newline characters intact. A simple loop over the file that prints the buffer content should naturally copy the file intact.
Second, use fread()
or the common C idiom with fgetc()
. These would process the file in fixed-size chunks or a single character at a time.
If you must process the file over white-space delimited strings, then use either fgets
or fread
to read the file, and something like strtok
to split the buffer at whitespace. Don't forget to handle the transition from one buffer to the next, since your target strings are likely to span the buffer boundary.
If there is an external requirement to use scanf
to do the reading, then limit the length of the string it might read with a precision field in the format specifier. In your case with a 999 byte buffer, then say scanf("%998s", str);
which will write at most 998 characters to the buffer leaving room for the nul terminator. If single strings longer than your buffer are allowed, then you would have to process them in two pieces. If not, you have an opportunity to tell the user about an error politely without creating a buffer overflow security hole.
Regardless, always validate the return values and think about how to handle bad, malicious, or just malformed input.
#include <stdio.h>
#include <stdlib.h>
int main() {
int num;
FILE *fptr;
if ((fptr = fopen("/root/Desktop/my_pass.txt","r")) == NULL) { // checks if file exists
puts("File not exists");
exit(1); // for exit(1) is required #include <stdlib.h>
} else
fscanf(fptr,"%d", &num);
printf("My pass is: %d\n", num);
fclose(fptr);
return 0;
}
You can use fgets
and limit the size of the read string.
char *fgets(char *str, int num, FILE *stream);
You can change the while
in your code to:
while (fgets(str, 100, file)) /* printf("%s", str) */;
You could read the entire file with dynamic memory allocation, but isn't a good idea because if the file is too big, you could have memory problems.
So is better read short parts of the file and print it.
#include <stdio.h>
#define BLOCK 1000
int main() {
FILE *f=fopen("teste.txt","r");
int size;
char buffer[BLOCK];
// ...
while((size=fread(buffer,BLOCK,sizeof(char),f)>0)
fwrite(buffer,size,sizeof(char),stdout);
fclose(f);
// ...
return 0;
}
참고URL : https://stackoverflow.com/questions/3463426/in-c-how-should-i-read-a-text-file-and-print-all-strings
'code' 카테고리의 다른 글
string.Empty vs null. 어떤 것을 사용합니까? (0) | 2020.10.10 |
---|---|
SQL 오류 errno : 121 (0) | 2020.10.09 |
텍스트를 클릭하여 해당 라디오 버튼 선택 (0) | 2020.10.09 |
Scala 컴파일에서 java.lang.OutOfMemoryError : PermGen 공간을 방지하는 방법은 무엇입니까? (0) | 2020.10.09 |
ListViewItem은 ListView의 너비로 늘어나지 않습니다. (0) | 2020.10.09 |