Cプログラムを作成して、既存のファイルの合計行数を検索します
読み取りモードでファイルを開きます。ファイルが存在する場合は、ファイルの行数をカウントするコードを記述します。ファイルが存在しない場合は、ファイルが存在しないというエラーが表示されます。
ファイルはレコードのコレクションです(または)データが永続的に保存されるハードディスク上の場所です。
以下はファイルに対して実行される操作です-
-
ファイルに名前を付ける
-
ファイルを開く
-
ファイルからの読み取り
-
ファイルへの書き込み
-
ファイルを閉じる
構文
以下は、ファイルを開いて名前を付けるための構文です-
1) FILE *File pointer;
Eg : FILE * fptr;
2) File pointer = fopen ("File name", "mode");
Eg : fptr = fopen ("sample.txt", "r");
FILE *fp;
fp = fopen ("sample.txt", "w"); プログラム1
#include <stdio.h>
#define FILENAME "Employee Details.txt"
int main(){
FILE *fp;
char ch;
int linesCount=0;
//open file in read more
fp=fopen(FILENAME,"r");
if(fp==NULL){
printf("File \"%s\" does not exist!!!\n",FILENAME);
return -1;
}
//read character by character and check for new line
while((ch=getc(fp))!=EOF){
if(ch=='\n')
linesCount++;
}
//close the file
fclose(fp);
//print number of lines
printf("Total number of lines are: %d\n",linesCount);
return 0;
} 出力
Total number of lines are: 3 Note: employee details.txt file consist of Pinky 20 5000.000000 Here total number of line are 3
プログラム2
このプログラムでは、フォルダに存在しないファイルの合計行数を見つける方法を説明します。
#include <stdio.h>
#define FILENAME "sample.txt"
int main(){
FILE *fp;
char ch;
int linesCount=0;
//open file in write mode
fp=fopen(FILENAME,"w");
printf ("enter text press ctrl+z of the end");
while ((ch = getchar( ))!=EOF){
fputc(ch, fp);
}
fclose(fp);
//open file in read more
fp=fopen(FILENAME,"r");
if(fp==NULL){
printf("File \"%s\" does not exist!!!\n",FILENAME);
return -1;
}
//read character by character and check for new line
while((ch=getc(fp))!=EOF){
if(ch=='\n')
linesCount++;
}
//close the file
fclose(fp);
//print number of lines
printf("Total number of lines are: %d\n",linesCount);
return 0;
} 出力
enter text press ctrl+z of the end Hi welcome to Tutorials Point C Pogramming Question & answers ^Z Total number of lines are: 2
-
Pythonプログラムを作成して、数値が強い数値であるかどうかを確認します
強い数字とは何ですか? 強い数とは、その桁の階乗の合計に等しい数です。 例 145 Factorial of 1=1 Factorial of 4=24 Factorial of 5=120 Sum=1+24+120 =145 次のプログラムは、入力された数が強い数であるかどうかを見つけることです。数値が強い数値の場合は「True」を返し、そうでない場合は「False」を返します。 2つの関数isStrong()を使用しています 数値が強いかどうかを判断する2番目のメソッドはfactorial() 渡された桁の階乗を返します。 階乗() isStro
-
数値の合計ビットをカウントするPythonプログラムを作成しますか?
最初に数値を入力し、bin()関数を使用してこの数値をバイナリに変換し、次に出力文字列の最初の2文字「0b」を削除し、次にバイナリ文字列の長さを計算します。 例 Input:200 Output:8 説明 Binary representation of 200 is 10010000 アルゴリズム Step 1: input number. Step 2: convert number into its binary using bin() function. Step 3: remove first two characters ‘0b’ of output binary st