问题
I need to read text from a file (text of few sentences) and then write down all unique characters. To do that I need to use an array. I wrote this code but it gives me nothing.
#include <stdio.h>
int main(void) {
int i;
FILE *in = fopen("test.txt", "r");
if (in) {
char mas[50];
size_t n = 0;
int ch;
while ((ch = getc(in)) != EOF) {
mas[n++] = (char)ch;
}
fclose(in);
}
for (i = 0; i < 50; i++) {
printf("%c", mas[i]);
printf("\n");
}
return 0;
}
回答1:
//low level input output commands method
#include <fcntl.h>
int main()
{
int x,i,n,v=1;
char s[256],str;
for (i=1;i<=255;i++)
s[i]='0';
x=open("out.txt",O_RDONLY);
if (x==-1)
{
printf("Invalid file path");
return 0;
}
while (n!=0)
{
n=read(x,&str,1);
s[(int)str]='1';
v=0;
}
close(x);
for (i=1;i<=255;i++)
if (s[i]=='1')
printf("%c",(char)i);
if (v)
printf("Blank file!");
close(x);
return 0;
}
回答2:
You have a problem with scope. mas was declared within your if block of code and has no visibility outside the if block. Move the declaration for mas outside the block. You need to keep n outside as well i.e.:
int i;
char mas[50];
size_t n = 0;
Next you fail to limit your read to less than 50 chars and will easily overflow mas. Add a check on n:
while ((ch = getc(in)) != EOF && n < 50) {
Finally limit your write of characters to the number read n:
for(i=0;i<n;i++)
That will compile and run. If you had compiled with warnings enabled, the compiler would have identified the scope problem for you. Always compile with -Wall -Wextra at a minimum.
回答3:
If you intend to read some char's to your array and print out unique one's check the below code
#include <stdio.h>
int main(void)
{
int i,j,flag;
char mas[50];
size_t n = 0;
FILE *in = fopen("test.txt", "r");
if (in) {
int ch;
while ((ch = getc(in)) != EOF && n < 50) {
mas[n++] = (char)ch;
}
fclose(in);
}
for(i=0;i<n;i++)
{
flag = 0;
for(j=i+1;j<n;j++)
{
if( mas[i] == mas[j])
{
flag = 1;
break;
}
}
if(!flag)
{
printf("%c\n",mas[i]);
}
}
return 0;
}
来源:https://stackoverflow.com/questions/27709595/how-to-put-text-from-file-into-array