2014-01-08 4 views
0
내가 파일에 구조의 배열을 삽입하려면 다음 코드를 사용

을 제기 할 수 있지만 충돌 :삽입 오류

void SaveInFile(List * pl) 
{ 

     int i; 
     int s = ListSize(pl); 

     file = fopen("myFile.txt", "w");  //3shan aktb 3la file mn gded 
     for (i = 0; i <= s; i++) { 
       file = fopen("myFile.txt", "a"); 
       fprintf(file, "IDOfprocess%s/n", pl->entry[i].ID); 
       fprintf(file, "IDOfprocess%s/n", pl->entry[i].BurstTime); 
     } 
     fclose(file); 
} 

어떤 생각 방법이 문제를 해결하기 위해?

+2

'ListSize' 다음, N 요소 목록 크기 N을 반환하는 경우 :'(I = 0 ; i ==; i ++)'''for (i = 0; i Maroun

+3

루프 내에서 (즉, 각 항목에 대해)'fopen() '을 호출합니다. 두 번째'fopen()'을 제거하십시오. 또한 'ID'와 '버스트 시간'은 어떤 데이터 유형입니까? 당신은 NULL로 끝나는 문자열을 의미하는 % s를 사용하고 있습니다. 그래서 그들은 참으로 문자열입니다. – cbranch

+1

1) 파일을 "a"모드로 먼저 열기, "자르지"않는 한, s + 1 번 열 수 없으므로, 2) lloop 내부에서 fopen을 제거하십시오. – ShinTakezou

답변

1

을해야

(그래서 당신은 s+1 요소와하지 s 요소를 치료하는) 0에서 시작 그것을 닫지 않고. 이 할 것 :

void SaveInFile(List* pl) 
{ 

int i; 
int s=ListSize(pl); 

file=fopen("myFile.txt","w");//3shan aktb 3la file mn gded 
fclose(file); 
for(i=0;i<=s;i++){ 

file=fopen("myFile.txt","a"); 
fprintf(file,"IDOfprocess%s/n",pl->entry[i].ID); 
fprintf(file,"IDOfprocess%s/n",pl->entry[i].BurstTime); 

fclose(file); 
} 
} 

파일을 닫지 않는 경우, 어떤 기록되지 않은 출력 버퍼의 내용을 파일에 기록되지 않습니다.

그러나 당신이 실제로해야하는 파일을 한 번 열려 있고 수행의 append 작업 :

void SaveInFile(List* pl) 
{ 

int i; 
int s=ListSize(pl); 

file=fopen("myFile.txt","w");//3shan aktb 3la file mn gded 
fclose(file); 

file=fopen("myFile.txt","a"); 
for(i=0;i<=s;i++){ 

fprintf(file,"IDOfprocess%s/n",pl->entry[i].ID); 
fprintf(file,"IDOfprocess%s/n",pl->entry[i].BurstTime); 
} 
fclose(file); 
} 
+0

당신은 여전히 ​​첫 번째 fopen을 닫아야합니다. 그렇지 않으면 리소스가 누출되었습니다 ... 단지 코멘트 일 수도 있습니다. –

+0

새 줄 쓰기 방법 \ n 새 줄이 아닌 같은 글자 인쇄 – AMH

+0

@ fernando.reyes done! 감사! –

1

당신의 for 루프는 s에 도달하고 당신은 그래서 당신은 파일을 여러 번 여는

for(i=0;i<s;i++){