dポイントプレゼントキャンペーン実施中!

現在、ヒストグラムのプログラムを作成しています。
まず0~255の1000個の乱数ファイルdata.txtを読み込み、
ヒストグラムは出来たのですが、
エクセルでグラフを作りたいので、
data1.txtに書き込みたいので、下のソースでやってみましたが、
0~255のカウントが全部0になってしまします。
fp = fopen("data1.txt","w");が無ければ正常に処理されます。

どうか教えてください。よろしくお願いします。

#include <stdio.h>
#define BUF 10
#define MAX 256

void count(FILE *fp , int* counter);

int main(void)
{
FILE *fp;
fp = fopen("data.txt","r");
fp = fopen("data1.txt","w");

int counter[MAX];
int i;
for(i=0 ; i<MAX ; i++)
{
counter[i] = 0;
}
count(fp , counter);
for(i=0 ; i<MAX ; i++)
{
printf("%d %d\n" , i, counter[i]);
}
fclose(fp);

return 0;
}

void count(FILE* p_file , int* counter)
{
char buf[BUF];
while (fgets(buf , BUF , p_file) != NULL)
{
int n;
sscanf(buf , "%d" , &n);
counter[n]++;
}
}

A 回答 (3件)

読み込みと書き込みの両方のファイルの変数がfpになっています。


別のファイルなんですから別の変数にしましょう。
fp2とか。
    • good
    • 0
この回答へのお礼

出来ました!
ありがとうございます。

お礼日時:2007/08/22 13:29

あっ、失礼しました^^;


わたしが意味を取り違えておりました。申し訳ありません。
以下のようですねかね(n が 0 以上、MAX 未満かなどはチェックしてませんが)。
====
#include <stdio.h>

#define MAX 256

int main(void)
{
FILE *fp = fopen("data.txt", "r");
int counter[MAX] = { 0 };
int i, n;
while (fscanf(fp, "%d", &n) == 1) ++counter[n];
fclose(fp);
fp = fopen("data1.txt", "w");
for (i = 0; i < MAX; ++i) fprintf(fp, "%d %d\n", i, counter[i]);
fclose(fp);
return 0;
}
    • good
    • 0
この回答へのお礼

こちらのソースファイルで動作することが出来ました。
ありがとうございます。

お礼日時:2007/08/22 13:29

ほんとにきちんと読めてますか?count()内でcounter[n]++; としているのとか。

。それに、書き出し用にオープンしているのに、書き出すときに標準出力に出しているようですし。。。エラー処理をしないとして、やりたいことは、
===
#include <stdio.h>

#define MAX 256

int main(void)
{
FILE *fp = fopen("data.txt", "r");
int counter[MAX] = { 0 };
int i, n = 0;
for (i = 0; i < MAX; ++i) {
if (fscanf(fp, "%d", counter + i) != 1) break;
++n;
}
fclose(fp);
fp = fopen("data1.txt", "w");
for (i = 0; i < n; ++i) fprintf(fp, "%d %d\n", i, counter[i]);
fclose(fp);
return 0;
}
===
こんな感じですか?読み込んだ個数をカウントしているので、counter の0での初期化は必要ありませんけどね(int counter[MAX]; で十分)。
    • good
    • 0

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!