I have a file like this:

2        |                                                 H|
2        |                                                 H|
2        |                                                 H|
2        |                                                 H|
2        |                                                 H|
2        |                                                 H|

& this code to read it in:

f = fopen(p, "r");	
				        char *t[100];
				        int i = 0;		
				        int i2 = 0;

					int n = atoi(optarg) - 1;		
					while (fscanf(f, "%s", line) != EOF) {
						if (i != n){
							printf("%s\n", line);
							t[i2] = strdup(line);
							i2++;
						}
						i++;
					}
					t[i2] = '\0';
					i2 = 0;
			       		fclose(f);
					f = fopen(p, "w");
					fprintf(f, "");
					fclose(f);
					f = fopen(p, "a");
					for (i2 = 0; t[i2] != '\0'; i2++)
			       		{	
						fprintf(f, "%s", t[i2]);
						free(t[i2]);
					}

when run:

|
H|
2
|
H|
2
|
H|
2
|
H|
2
|
H|
2
|
H|

I expected the output to look like the file, whats wrong?

Recommended Answers

All 3 Replies

Try it,

char word[3][10];
while (fscanf(f, "%s%s%s",word[0],word[1],word[2])!=EOF) {
     printf("\n%s   %s    %s   %s",word[0],word[1],word[2]);
 }

pymatio> I expected the of output to look like the file, whats wrong?
Your understanding of how fscanf() works.
pymatio>

while (fscanf(f, "%s", line) != EOF) {

"%s" won't read a line but rather until encounters an space, blank, tab, newline.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.