【问题标题】:C - Program that reads from file.txt only odd linesC - 仅从 file.txt 读取奇数行的程序
【发布时间】:2017-11-27 19:50:36
【问题描述】:

我在执行程序时遇到问题,它将具有 3 个功能:void read(char *file name(程序将从该文件读取并从终端中奇数行打印文本)...)、void write (char *file_name1(程序将从输入文件的奇数行写入字符数),char *file_name2(程序将从行中写入二进制数的字符 - 从输入文件 - 具有奇数)...)和 main 将这些文件的名称作为参数。然后我将能够使用以下内容启动程序:./a.out input.txt output.txt output.bin 在主函数中,我有 char 数组 [10] [80]。总之,我想从输入文件 .txt 中读取前 10 行,然后在终端中写入具有奇数索引的行,然后将这些行中的字符数(作为文本和二进制)保存在两个文件中:.txt 和 .bin。

#include <stdio.h>
#include <string.h>
#define N 10
#define M 80


void read(char *file_name){
FILE *file_name;
file_name=fopen(".txt", "r");
char tab[80];
if (input==NULL) {
        printf("Error opening file");
        exit(-1);
        }
while(!feof(input)){
    fgets(tab, 80, input);
 }
}

void write(){
}


int main(int argc, char *argv[]){
char TEKST[N][M];
read(argv[1]);
write(argv[2], argv[3]);

return 0;
}

这是我开始编写的代码。我不知道如何将输入文件名作为参数传递给 fopen 函数,如何在终端中仅打印带有来自输入文件的奇数索引的文本行。以及如何计算这些行中的字符并将它们保存到 2 个文件:.txt 和 .bin。

提前致谢!

【问题讨论】:

  • 嗨!你的问题是……? ...How to ask a good question
  • 请贴出你已经写好的代码。
  • 从哪里开始? 1. FILE *file_name; - 使用与函数参数相同的变量名。 2. 不检查返回值 - 你打开文件了吗? 3 您确定要打开的文件名为.txt。当 this 用于 io 时调用函数 read。 4. input - 这是在哪里声明的? 5.这样编译吗.....

标签: c arrays file


【解决方案1】:

我想你会得到第一行,把它放到你的输出字符串中,然后得到下一行并丢弃它。重复此操作,直到文件结束。

类似这样的:

#include <stdio.h>
#include <string.h>

int main()
{
    //open the file
    FILE * file;
    file = fopen("file.txt", "r");

    //the max number of characters per line
    const int maxCharsPerLine = 100; //you can change this number to whatever you want

    //the maximum amout of characters you want on the output
    const int maxOutputChars = 1000; //you can change this number to whatever you want

    //a c string to hold a single line of data at a time
    char currLine[maxCharsPerLine];

    //a c string to hold the odd lines of data
    char oddLines[maxOutputChars];
    memset(oddLines, 0, sizeof(oddLines));

//a c string to hold the even lines of data
char evenLines[maxCharsPerLine];

//while you are not at the end of the file
while (/*get a line of characters*/ fgets(currLine, maxCharsPerLine, file) != NULL)
{
    //update the line of characters
    strcat(oddLines, currLine);

    //discard a line of characters
    fgets(evenLines, maxCharsPerLine, file);
    memset(evenLines, 0, sizeof(evenLines));
}
fclose(file);

//print the odd lines
printf("%s", oddLines);
}

【讨论】:

  • 嗨 Joshua - 欢迎来到 StackOverflow。根据这个问题的编写方式,我认为这个用户需要一些代码本身的帮助,而不仅仅是算法。如果您可以提供帮助(请记住问题中的 cmets),请这样做。
猜你喜欢
  • 2016-06-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多