第二,我是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
答案 0 :(得分:0)
您可以这样做:
#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);
}