从任何数据函数读取打印行

Read print lines from any data function

其次,在我的作业中,我是 C 程序用户的新手,但太落后了。我必须解决今天到期的问题。我主要认为(我理解文件的功能真的很复杂)应该使用 fscan 来读取文件并输出文件中的新行。该文件也包括在内,例如我正在使用的。我知道 5 点看起来很尴尬但我是 C 程序的新手并且从未完成过 C 程序的功能部分。我想用 i 输出来计算要打印的每一行。我还想在评论中包含一些帮助信息。对于函数,第一次不知道fooen和fgets的代码写什么

例如:

Example input/output:
   ./a.out testfile

   1: Bob
   2: Tiffany
   3: Steve
   4: Jim
   5: Lucy
   ...
/* 5 points */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXLEN 1000
#define MAX_LINE_LEN 4096
/**
 * Complete the function below that takes an array of strings and a integer
 * number representing the number of strings in the array and prints them out to
 * the screen with a preceding line number (starting with line 1.)
 */
void
printlines (char *a[], int n)
{

}    
/**
 * Create a main function that opens a file composed of words, one per line
 * and saves them to an array of MAXLEN strings that is then printed using
 * the above function.
 *
 * Hints:
 *  - Use fopen(3) to open a file for reading, the the returned file handle *    with the fscanf() function to read the words out of it.
 *  - You can read a word from a file into a temporary word buffer using the
 *    fscanf(3) function.
 *  - You can assume that a word will not be longer than MAXLEN characters.
 *  - Use the strdup(3) function to make a permanent copy of a string that has
 *    been read into a buffer.
 * 
 * Usage: "Usage: p7 <file>\n"
 * 
 * Example input/output:
 * ./p7 testfile
 *  1: Bob
 *  2: Tiffany
 *  3: Steve
 *  4: Jim
 *  5: Lucy
 * ...
 */
int main (int argv, char *argc[])
{  if (argc < 2)
    {
      printf ("Usage: p7 <file>\n");
    }
      char buffer[MAX_LINE_LEN];

  /* opening file for reading */
  FILE *fp = fopen (argv[1], "r");
  if (!fp)
    {
      perror ("fopen failed");      exit (EXIT_FAILURE);
    }

  int i = 0;
  while ((i <= MAX_LINES) && (fgets (buffer, sizeof (buffer), fp)))
    {
      printf ("%2i: %s", i, buffer); //i is to count from each lines
      i++;
    }
  fclose (fp);
  return (0);


}

查看testfile

Bob
Tiffany
Steve
Jim
Lucy
Fred
George
Jill
Max
Butters
Randy
Dave
Bubbles

你可以这样做:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXLEN 1000
#define MAX_LINE_LEN 4096

void printlines (char *a[], int n)
{
    for (int i = 0; i != n; ++i)
        printf("%2d: %s\n", i, a[i]);
}

int main (int argc, char *argv[])
{  
    if (argc < 2)
    {
        printf ("Usage: p7 <file>\n");
        return -1;
    }

    FILE *fp = fopen (argv[1], "r");
    if (!fp)
    {
        perror ("fopen failed");
        exit (EXIT_FAILURE);
    }

    char* a[MAXLEN];
    char buffer[MAX_LINE_LEN];
    int i = 0;
    while (i < MAXLEN && fscanf(fp, "%s", buffer) == 1)
        a[i++] = strdup(buffer);
    printlines(a, i);
    fclose (fp);
    return (0);
}