簡體   English   中英

如何從文件中獲取奇數和偶數行號的文本並將它們寫入新文件?

[英]How to take odd and even line numbers of text from a file and write them to new files?

我有一個項目,它是這樣的。 我需要將一些文本寫入文件,並且該文本有幾行。 然后如果該行的編號是奇數,它應該被寫入odd_linenumber_texts 文件。 如果該行的編號是偶數,則應將其寫入 even_linenumber_texts 文件。 我在許多網站上搜索過它,但我只找到了分隔數字而不是文本行號的代碼。 實際上,這接近我想要做的。 如何通過奇數/偶數分隔行數並寫入必要的文件。 這是我發現的:

#include <stdio.h>
#include <stdlib.h>
int isEven(const int NUM);
int isPrime(const int NUM);
int main()
{
FILE * fp,
     * fpEven, 
     * fpOdd; 

int num, success;

fp = fopen("data/numbers.txt", "r");
fpEven = fopen("data/even-numbers.txt" , "w");
fpOdd  = fopen("data/odd-numbers.txt"  , "w");

if(fp == NULL || fpEven == NULL || fpOdd == NULL)
{
    printf("Unable to open file.\n");
    exit(EXIT_FAILURE);
}

while (fscanf(fp, "%d", &num) != -1)
{
    if (isEven(num))
        fprintf(fpEven, "%d\n", num);
    else
        fprintf(fpOdd, "%d\n", num);
}
fclose(fp);
fclose(fpEven);
fclose(fpOdd);
return 0;
}

嘗試

int num = 1;

while (fscanf(fp, "%d", &num) != -1)
{
    if (isEven(num))
        fprintf(fpEven, "%d\n", num);
    else
        fprintf(fpOdd, "%d\n", num);

    num++;
}

實際上,您想每隔一行寫一個不同的文件。 無需測試行號是偶數還是奇數:

...
int even = 0;                        // first line will be odd
while (fscanf(fp, "%d", &num) != -1)
{
    if (even)
        fprintf(fpEven, "%d\n", num);
    else
        fprintf(fpOdd, "%d\n", num);
    even = 1 - even;                  // flip even on each line
}

我重新排列了我的代碼,我不知道它是否真的有效。 我需要這樣做。 打開奇數文件,打印第 1 行,第 3 行,第 5 行。然后操作偶數文件,打印第 2 行,第 4 行,第 6 行。

#include <stdio.h> 
#include <stdlib.h> 
int isEven(const int NUM);
int isPrime(const int NUM);
int main() 
{ 
char name[64];
FILE * fp,
     * fpEven, 
     * fpOdd; 

int num, success;
 printf("Dosya ismi: ");
 fgets(name, 64, stdin);
 fp = fopen("data/numbers.txt", "w+");
 fputs("Line 1", fp);
 fputs("Line 2", fp);
 fputs("Line 3", fp);
 fputs("Line 4", fp);
 fputs("Line 5", fp);
 fputs("Line 6", fp);
 fpEven = fopen("data/even-numbers.txt" , "w");
 fpOdd  = fopen("data/odd-numbers.txt"  , "w");

if(fp == NULL || fpEven == NULL || fpOdd == NULL)
{
    printf("Unable to open file.\n");
    exit(-1);
}
 int even = 0;                        
 while (fscanf(fp, "%d", &num) != -1)
 {
 if (even)
    fprintf(fpEven, "%d\n", num);
 else
    fprintf(fpOdd, "%d\n", num);
 even = 1 - even;                   
 }
 fclose(fp);
 fclose(fpEven);
 fclose(fpOdd);
 return 0;
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM