내 수업에서는 C에서 운영 체제 시뮬레이터를 작성해야합니다. 첫 번째 프로젝트는 구성 파일과 메타 데이터 파일 두 개를 읽는 것이 었습니다. 완성 된 코드를 실행하는 첫 번째 시도는 세분화 오류 (나는 이것이 내가 해결했다고 믿는다)로 이끌었다. 이제 fgets 문을 줄 단위로 읽는 데 문제가 있습니다. 모든 행을 읽지 만 행을 읽지 않습니다. 프로세스를 끝낼 때까지 파일을 무한정 읽습니다. while 루프에 printf 문을 써서 읽고있는 내용을 볼 수 있으며 각 줄을 살펴볼 수 있습니다.C에서 줄 단위로 파일을 읽으려고 시도했지만 while 루프가 끝나지 않습니다
int readCfgFile (char *filename, CONFIG *filedata)
{
char buffer[255], trash[255];
FILE *cfgfile = malloc(sizeof cfgfile);
cfgfile = fopen(filename, "r"); // Assumed where segfault was
if(!cfgfile)
{
return -2; // Error opening file
}
char *schedulingCode = malloc(8);
char *logToCode = malloc(200);
char *tempLine; // Suggested to me as a fix (the using a separate variable part)
fgets(trash, 255, cfgfile); //Trash the first line of the file
tempLine = fgets(buffer, 255, cfgfile);
while(tempLine != NULL)
{
sscanf(buffer, "Version/Phase: %d", &filedata->version);
sscanf(buffer, "File Path: %s", filedata->metaPath);
sscanf(buffer, "CPU Scheduling Code: %s", schedulingCode);
sscanf(buffer, "Quantum Time (cycles): %d", &filedata->quantum);
sscanf(buffer, "Memory Available (KB): %d", &filedata->memory);
sscanf(buffer, "Processor Cycle Time (msec): %d", &filedata->processTime);
sscanf(buffer, "I/O Cycle Time (msec): %d", &filedata->ioTime);
sscanf(buffer, "Log To: %s", logToCode);
sscanf(buffer, "Log File Path: %s", filedata->logPath);
tempLine = fgets(buffer, 255, cfgfile);
if(tempLine == NULL)
{
break;
}
printf("%s\n", buffer);
}
파일은 다음과 같습니다
Start Simulator Configuration File
Version/Phase: 1.0
File Path: Test_3.mdf
CPU Scheduling Code: NONE
Quantum Time (cycles): 55
Memory Available (KB): 667
Processor Cycle Time (msec): 10
I/O Cycle Time (msec): 20
Log To: Monitor
Log File Path: logfile_1.lgf
End Simulator Configuration File.
사람이 while 루프가 영원히 계속 유지하는 이유 어떤 생각을 가지고 있습니까?
char * logToCode = malloc (sizeof logToCode); -> char * logToCode = malloc (200);'if (버퍼 == NULL)'->'if (tempLine == NULL) ','char * schedulingCode = malloc (sizeof schedulingCode);'char * schedulingCode = malloc (8);'char * tempLine; ,'FILE * cfgfile = malloc (sizeof cfgfile);'->'FILE * cfgfile; ' – BLUEPIXY
제안 사항을 업데이트했지만 여전히 멈추지 않습니다. Windows의 우분투에서 Bash에 대한 코드를 컴파일하고 실행하는 것에 대해 언급해야 할 것입니다. 파일 포인터의 크기를 할당하지 않으면 분할 오류가 발생합니다. 적어도 나는 그 문제가 어디에 있는지 안다. –