C_C++
(C언어) 성적 데이터 파일 읽기 fscanf, fscanf_s
고니자니
2022. 11. 23. 09:20
반응형
다음과 같은 형식의 성적 데이터를 읽어 들이는 C언어 코드입니다.
정재욱 100 100 100 이순신 90 91 92 홍길동 81 82 83 |
C언어 코드
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main()
{
FILE* fp;
char name[20];
int a, b, c, tot;
if ((fp = fopen("score.txt", "r")) == NULL)
{
printf("파일을 열 수 없습니다.\n");
return -1;
}
while (!feof(fp))
{
fscanf(fp, "%s %d %d %d", name, &a, &b, &c);
tot = a + b + c; // 총점 구하기
printf("%s\t%3d %3d %3d %3d\n", name, a, b, c, tot);
}
fclose(fp);
return 0;
}
위 코드를 fscanf_s 함수를 사용하는 코드로 수정했습니다.
비주얼스튜디오(Visual Studio)에서 사용하는 형식입니다.
// #define _CRT_SECURE_NO_WARNINGS -- 이 코드는 필요 없습니다.
#include <stdio.h>
int main()
{
FILE* fp;
char name[20];
int a, b, c, tot;
errno_t err;
err = fopen_s(&fp, "score.txt", "r"); // fopen_s
if(err != 0)
{
printf("파일을 열 수 없습니다.\n");
return -1;
}
while (!feof(fp))
{
fscanf_s(fp, "%s %d %d %d", name, 10, &a, &b, &c); // fscanf_s, %s다음에 문자열 길이
tot = a + b + c;
printf("%s\t%3d %3d %3d %3d\n", name, a, b, c, tot);
}
fclose(fp);
return 0;
}
C++ 코드가 필요하면 아래 링크 클릭 ↙↙↙
https://gonyzany.tistory.com/174
(C++) 성적 데이터 파일 읽기 ifstream
#파일 #읽기 #fstream #ifstream 아래와 같은 형식의 데이터를 읽는 C++ 코드입니다. 정재욱 100 100 100 이순신 90 91 92 홍길동 81 82 83 C++ 코드 #include #include using namespace std; int main() { ifstream fin("score.txt"); if
gonyzany.tistory.com
반응형