I am trying to read a graph from file, I got on the first line the nodes, and I made a code that reads the nodes in the vector until the end of the line, then on the second like I got the arcs, in the (%d %d) format. My problem is that when I try to read the nodes, it skips the first number, third, and so on. And I cannot figure out why.
Here is my code:
void readGraph() {
int i=0, j, node1, node2, n,check1, check2,c;
char nodes[MAXN];
FILE *f;
f = fopen("data.in","r");
if (f == NULL) {
printf("Error in opening file!");
}
else {
while ((c = fgetc(f)) != EOF) {
if ( c != ' ') {
fscanf(f, "%d", &(nodes[i]));
printf("%d, %d\n",i,nodes[i]);
i++;
}
if (c == '\n')
break;
}
}
while (fscanf(f,"(%d %d)", &node1, &node2)) {
if ( c != ' ')
fscanf(f, "(%d %d) ", &node1, &node2);
if (c == '\n')
break;
}
fclose(f);
}
Also, my data.in:
1 2 3 4 5 6
(1 3) (2 3) (3 4) (3 5) (3 6) (4 6) (5 6)
Any help will be much appreciated. Thanks!
I am guessing, fgetc reads byte by byte, and fscanf("%d") reads 4 bytes at a time, so this could cause some issue.
while ((c = fgetc(f)) != EOF) {
if ( c != ' ') {
fscanf(f, "%d", &(nodes[i]));
printf("%d, %d\n",i,nodes[i]);
i++;
}
if (c == '\n')
break;
}
Here you read twice from f (fgetc(f) is discarded)
For the arcs (code below) there's also a problem, you test c but you're not reading it any more
while (fscanf(f,"(%d %d)", &node1, &node2)) {
if ( c != ' ')
fscanf(f, "(%d %d) ", &node1, &node2);
if (c == '\n')
break;
}
try this solution and you can see my c comments:
void readGraph() {
int i=0, j, node1, node2, n,check1, check2,c;
char nodes[128];
FILE *f;
f = fopen("data.in","r");
if (f == NULL) {
printf("Error in opening file!");
}
else {
while (((c = fgetc(f)) != EOF) && (c != '\n')) {
if ( c != ' ') {
nodes[i] = c;
/*fscanf(f, "%d", &(nodes[i]));*/ // you loose read c value when you read again without using value
printf("%d, %c\n",i,nodes[i]);
i++;
}
/*if (c == '\n')
break;*/
/* You loop 1 extra time */
}
}
while (fscanf(f,"(%d %d)", &node1, &node2)) {
if ( c != ' ')
fscanf(f, "(%d %d) ", &node1, &node2);
if (c == '\n')
break;
}
fclose(f);
}
void readGraph(void){
int i = 0, j, node1, node2, n, check1, check2, c;
int nodes[MAXN];
FILE *f;
f = fopen("data.in","r");
if (f == NULL) {
printf("Error in opening file!");
return ;
}
while ((c = fgetc(f)) != EOF) {
if( c == ' ')
continue;
else if( c == '\n')
break;
else {
ungetc(c, f);//It is too reading. So Return the character to the stream.
fscanf(f, "%d", &nodes[i]);
printf("%d, %d\n", i, nodes[i]);
i++;
}
}
while (2 == fscanf(f,"(%d %d) ", &node1, &node2)) {
printf("(%d, %d)\n", node1, node2);
}
fclose(f);
}
Related
My task is to create a C program that opens a .c file in which the user then writes some text then said text is printed along with the number of (){}/ and the percentage ratio comments:whole text of the C program.
So far I've this:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int k, j, m, n, l, z, count1 = 0, count2 = 0, count3 = 0, count4 = 0, count5 = 0, count6 = 0;
char str[10000], chh, chhh;
char ch, file_name[75];
FILE *fp;
printf("Enter the name of file you wish to see with extension .c or .txt\n");
gets_s(file_name);
fp = fopen_s(file_name, "r"); // reads the file
if (fp == NULL)
{
perror("Error while opening the file.\n");
_getche();
exit(EXIT_FAILURE);
}
printf("The contents of %s file are :\n", file_name); //prints out the text
int i = 0;
while ((ch = fgetc(fp)) != EOF) {
printf("%c", ch);
str[i] = ch;
i++;
}
int fsize = i;
// code above opens up the symbols of the file, code below searches for specific symbols
int count = 0;
printf("\nEnter the character to be searched : "); //which symbol to search
scanf_s("%c", &chh);
for (i = 0; i < fsize; i++) {
if (str[i] == chh)
count++;
}
if (count == 0)
printf("\nCharacter '%c' is not present", chh); //if there isn't one
else
printf("\nOccurence of character '%c' : %d", chh, count); //prints their number if there is
for (k = 0; k<fsize; k++) {
if (str[k] == '>')
count1++;
}
for (j = 0; j<fsize; j++) {
if (str[j] == '<')
count2++;
}
for (m = 0; m<fsize - 1; m++) {
if (str[m] == '=' && str[m + 1] == '=')
count3++;
}
for (n = 0; n<fsize - 4; n++) {
if (str[n] == 'e' && str[n + 1] == 'l' && str[n + 2] == 's' && str[n + 3] == 'e')
count4++;
}
for (l = 0; l<fsize - 2; l++) {
if (str[l] == 'i' && str[l + 1] == 'f')
count5++;
}
int br;
br = count4 + count5;
printf("\nOccurence of character '%c' : %d", '>', count1);
printf("\nOccurence of character '%c' : %d", '<', count2);
printf("\nOccurence of character == : %d ", count3);
printf("\nOccurence of character else : %d ", count4);
printf("\nOccurence of character if: %d \n", count5);
printf("\nobsht broi if+else: %d ", br);
fclose(fp);
return 0;
}
It prints out the text inside a file, searches for a specific character you want and prints out its occurrence.
PS: when I try to run it on my PC, Visual Studio spits out a bunch of errors and warnings. I'm puzzled as to how to get rid of them.
Errors image
Thanks !
Using GCC I was able to compile this by changing a few methods.
changed gets_s to gets(file_name) which produces a warning that this is an unsafe function.
changed _getche() to getchar()
changed scanf_s() to scanf()
change fopen_s() to fopen()
This code compiled and ran using GCC on Linux
#include <stdio.h>
#include <stdlib.h>
int main()
{
int k, j, m, n, l, z, count1 = 0, count2 = 0, count3 = 0, count4 = 0, count5 = 0, count6 = 0;
char str[10000], chh, chhh;
char ch, file_name[75];
FILE *fp;
printf("Enter the name of file you wish to see with extension .c or .txt\n");
gets(file_name);
fp = fopen(file_name, "r"); // reads the file
if (fp == NULL)
{
perror("Error while opening the file.\n");
getchar();
exit(EXIT_FAILURE);
}
printf("The contents of %s file are :\n", file_name); //prints out the text
int i = 0;
while ((ch = fgetc(fp)) != EOF) {
printf("%c", ch);
str[i] = ch;
i++;
}
int fsize = i;
// code above opens up the symbols of the file, code below searches for specific symbols
int count = 0;
printf("\nEnter the character to be searched : "); //which symbol to search
scanf("%c", &chh);
for (i = 0; i < fsize; i++) {
if (str[i] == chh)
count++;
}
if (count == 0)
printf("\nCharacter '%c' is not present", chh); //if there isn't one
else
printf("\nOccurence of character '%c' : %d", chh, count); //prints their number if there is
for (k = 0; k<fsize; k++) {
if (str[k] == '>')
count1++;
}
for (j = 0; j<fsize; j++) {
if (str[j] == '<')
count2++;
}
for (m = 0; m<fsize - 1; m++) {
if (str[m] == '=' && str[m + 1] == '=')
count3++;
}
for (n = 0; n<fsize - 4; n++) {
if (str[n] == 'e' && str[n + 1] == 'l' && str[n + 2] == 's' && str[n + 3] == 'e')
count4++;
}
for (l = 0; l<fsize - 2; l++) {
if (str[l] == 'i' && str[l + 1] == 'f')
count5++;
}
int br;
br = count4 + count5;
printf("\nOccurence of character '%c' : %d", '>', count1);
printf("\nOccurence of character '%c' : %d", '<', count2);
printf("\nOccurence of character == : %d ", count3);
printf("\nOccurence of character else : %d ", count4);
printf("\nOccurence of character if: %d \n", count5);
printf("\nobsht broi if+else: %d \n", br);
fclose(fp);
return 0;
}
Please find my findings below.
gets_s(file_name); -> i dont think this is correct. gets_s Takes up 2 argument and not 1 please use gets instead and try it out or simple scanf to check if it is working.
2._getche() Please use #include header file for that function. Using it would avoid this issue.
fopen_s -> Fopen has invalid set of arguments. U need a file pointer as the first argument. Please re-frame the function used. Better go for fopen which has 2 arguments.
scanf_s -> has an argument(parameter) where you can specify the buffer size. Hence the above code sacnf_s function u have used is syntaticaly wrong. Please change it accordingly.
Please find the changed code which is commonly used. I have taken the liberty of changing the gets_s to gets, fopen_s to fopen and scanf_s to scanf and have build it. No errors. Please find the code below for your reference.
#include <stdio.h>
#include <stdlib.h>
#include<conio.h>
FILE *fp;
int main()
{
int k, j, m, n, l, z, count1 = 0, count2 = 0, count3 = 0, count4 = 0, count5 = 0, count6 = 0;
char str[10000], chh, chhh;
char ch, file_name[75];
printf("Enter the name of file you wish to see with extension .c or .txt\n");
gets(file_name);
fp = fopen(file_name, "r"); // reads the file
if (fp == NULL)
{
perror("Error while opening the file.\n");
getchar();
exit(EXIT_FAILURE);
}
printf("The contents of %s file are :\n", file_name); //prints out the text
int i = 0;
while ((ch = fgetc(fp)) != EOF) {
printf("%c", ch);
str[i] = ch;
i++;
}
int fsize = i;
// code above opens up the symbols of the file, code below searches for specific symbols
int count = 0;
printf("\nEnter the character to be searched : "); //which symbol to search
scanf_s("%c", &chh);
for (i = 0; i < fsize; i++) {
if (str[i] == chh)
count++;
}
if (count == 0)
printf("\nCharacter '%c' is not present", chh); //if there isn't one
else
printf("\nOccurence of character '%c' : %d", chh, count); //prints their number if there is
for (k = 0; k<fsize; k++) {
if (str[k] == '>')
count1++;
}
for (j = 0; j<fsize; j++) {
if (str[j] == '<')
count2++;
}
for (m = 0; m<fsize - 1; m++) {
if (str[m] == '=' && str[m + 1] == '=')
count3++;
}
for (n = 0; n<fsize - 4; n++) {
if (str[n] == 'e' && str[n + 1] == 'l' && str[n + 2] == 's' && str[n + 3] == 'e')
count4++;
}
for (l = 0; l<fsize - 2; l++) {
if (str[l] == 'i' && str[l + 1] == 'f')
count5++;
}
int br;
br = count4 + count5;
printf("\nOccurence of character '%c' : %d", '>', count1);
printf("\nOccurence of character '%c' : %d", '<', count2);
printf("\nOccurence of character == : %d ", count3);
printf("\nOccurence of character else : %d ", count4);
printf("\nOccurence of character if: %d \n", count5);
printf("\nobsht broi if+else: %d ", br);
fclose(fp);
return 0;
}
At any point of time if u need any assistance please ping me :) Thank you.
Program takes an input file through the command line and outputs the occurrence of each letter in the text file. Not sure where I went wrong.
int main(int argc, char *argv[]) {
char word[1000];
int a = 0;
int b = 0;
int d = 0;
int c = 0;
int e = 0;
int f = 0;
int g = 0;
int h = 0;
int i = 0;
int j = 0;
int k = 0;
int l = 0;
int m = 0;
int n = 0;
int o = 0;
int p = 0;
int q = 0;
int r = 0;
int s = 0;
int t = 0;
int u = 0;
int v = 0;
int w = 0;
int x = 0;
int y = 0;
int z = 0;
int other = 0;
int counter, lenght;
FILE *fp = fopen(argv[1], "r");
fgets(word, 999, fp);
lenght = 1000;
for(counter = 0; counter < lenght; counter++) {
word[counter] = tolower(word[counter]);
if (word[counter] == 'a') {
a++;
}
else if (word[counter] == 'b') {
b++;
}
else if (word[counter] == 'c') {
c++;
}
else if (word[counter] == 'd') {
d++;
}
else if (word[counter] == 'e') {
e++;
}
else if (word[counter] == 'f') {
f++;
}
else if (word[counter] == 'g') {
g++;
}
else if (word[counter] == 'h') {
h++;
}
else if (word[counter] == 'i') {
i++;
}
else if (word[counter] == 'j') {
j++;
}
else if (word[counter] == 'k') {
k++;
}
else if (word[counter] == 'l') {
l++;
}
else if (word[counter] == 'm') {
m++;
}
else if (word[counter] == 'n') {
n++;
}
else if (word[counter] == 'o') {
o++;
}
else if (word[counter] == 'p') {
p++;
}
else if (word[counter] == 'q') {
q++;
}
else if (word[counter] == 'r') {
r++;
}
else if (word[counter] == 's') {
s++;
}
else if (word[counter] == 't') {
t++;
}
else if (word[counter] == 'u') {
u++;
}
else if (word[counter] == 'v') {
v++;
}
else if (word[counter] == 'w') {
w++;
}
else if (word[counter] == 'x') {
x++;
}
else if (word[counter] == 'y') {
y++;
}
else if (word[counter] == 'z') {
z++;
}
else {
other++;
}
}
printf("\nCharacter frequency in %s", argv[1]);
printf("\nCharacter Count");
printf("\na \t\t %d", a);
printf("\nb \t\t %d", b);
printf("\nc \t\t %d", c);
printf("\nd \t\t %d", d);
printf("\ne \t\t %d", e);
printf("\nf \t\t %d", f);
printf("\ng \t\t %d", g);
printf("\nh \t\t %d", h);
printf("\ni \t\t %d", i);
printf("\nj \t\t %d", j);
printf("\nk \t\t %d", k);
printf("\nl \t\t %d", l);
printf("\nm \t\t %d", m);
printf("\nn \t\t %d", n);
printf("\no \t\t %d", o);
printf("\np \t\t %d", p);
printf("\nq \t\t %d", q);
printf("\nr \t\t %d", r);
printf("\ns \t\t %d", s);
printf("\nt \t\t %d", t);
printf("\nu \t\t %d", u);
printf("\nv \t\t %d", v);
printf("\nw \t\t %d", w);
printf("\nx \t\t %d", x);
printf("\ny \t\t %d", y);
printf("\nz \t\t %d", z);
fclose(fp);
return 0;
}
Should output in two columns one being the letter and the next being the number of times that letter occurs
There are problems in your code:
you do not include <stdio.h> nor <ctype.h>
you only read one line and you do not even check if that succeeds. You should write a loop like while (fgets(word, sizeof word, fp)) {
you check all characters in the word array: you should stop at the end of the line: lenght = strlen(word);
tolower() should not be given a char argument, because on platforms where char is signed, negative values invoke undefined behavior. You can cast the argument as (unsigned char) to avoid this: word[counter] = tolower((unsigned char)word[counter]);
More room for improvement:
lenght is misspelt, it should be length.
you should use an array of counters to avoid all these tests and all these explicit printf statements.
check the argument count and fopen() success
no need to read line by line, handle one byte at a time read with getc(). However, reading one large chunk at a time can be faster because it uses fewer tests and locks.
the printf statements should output the newline at the end rather than at the beginning.
Here is a corrected and simplified version:
#include <ctype.h>
#include <limits.h>
#include <stdio.h>
int main(int argc, char *argv[]) {
int count[UCHAR_MAX + 1] = { 0 };
int other, total;
int c;
const char *s;
FILE *fp;
if (argc <= 1) {
fprintf(stderr, "missing input file\n");
return 1;
}
fp = fopen(argv[1], "r");
if (fp == NULL) {
fprintf(stderr, "cannot open input file %s\n", argv[1]);
return 1;
}
total = 0;
while ((c = getc(fp)) != EOF) {
count[tolower(c)] += 1;
total++;
}
printf("Character frequency in %s\n", argv[1]);
printf("Character Count\n");
other = total;
for (s = "abcdefghijklmnopqrstuvwxyz"; *s; s++) {
printf("%c:\t%9d\n", *s, count[(unsigned char)*s]);
other -= count[(unsigned char)*s];
}
printf("other:\t%9d\n", other);
fclose(fp);
return 0;
}
Reading the file by chunks instead of one byte at a time improves the speed dramatically with recent C libraries, because the support for multithreading has made the getc() macros inefficient. Using 64K buffers, the code below is fifty times faster (50X) for a 400MB file:
#include <ctype.h>
#include <limits.h>
#include <stdio.h>
#define BUFFER_SIZE 65536
int main(int argc, char *argv[]) {
unsigned char buffer[BUFFER_SIZE];
long count[UCHAR_MAX + 1] = { 0 };
long other;
size_t i, n;
const char *s;
FILE *fp;
if (argc <= 1) {
fprintf(stderr, "missing input file\n");
return 1;
}
fp = fopen(argv[1], "r");
if (fp == NULL) {
fprintf(stderr, "cannot open input file %s\n", argv[1]);
return 1;
}
while ((n = fread(buffer, 1, sizeof buffer, fp)) != 0) {
for (i = 0; i < n; i++) {
count[buffer[i]] += 1;
}
}
other = 0;
for (i = 0; i <= UCHAR_MAX; i++) {
if (isupper(i)) {
count[tolower(i)] += count[i];
} else {
if (!islower(i))
other += count[i];
}
}
printf("Character frequency in %s\n", argv[1]);
printf("Character Count\n");
for (s = "abcdefghijklmnopqrstuvwxyz"; *s; s++) {
printf("%c:\t%9ld\n", *s, count[(unsigned char)*s]);
}
printf("other:\t%9ld\n", other);
fclose(fp);
return 0;
}
Here's a quick implementation I wrote. It doesn't use fgets, but that is most definitely an option.
The flow of the program should be simple, but it is as follows:
Check for a proper argument count.
Declare the variables we'll need.
Declare the file pointer and attempt to open the file.
If the file doesn't open, we'll error out.
Read in every character from the file one at a time and store it into our variable c.
Using our ascii table, we'll alter the values to get them into the proper position in our array.
Print out all of our values.
Close the file.
#include <stdio.h>
int main(int argc, char **argv){
if (argc < 2){
printf("Not enough arguments!\n");
return -1;
}
int A[27] = {0}, c;
FILE *inFile = fopen(argv[1], "r");
if (inFile == NULL){
printf("The file \"%s\" could not be opened.\n", argv[1]);
return -2;
}
while((c = fgetc(inFile)) != EOF){
if ( c >= 'a' && c <= 'z' ){
/* C is a lowercase character */
c-='a';
A[c]++;
}
else if ( c >= 'A' && c <= 'Z' ){
/* C is an uppercase character */
c-='A';
A[c]++;
}
else if (c == '\n'){
/* we're not counting newlines */
continue;
}
else {
A[26]++;
}
}
/* Print out all the values except the "Other" count. */
for (c = 0; c < sizeof A / sizeof A[0] - 1; c++){
printf("%c: %d\n", c+'a', A[c]);
} printf("Other: %d\n", A[26]); //Print out "Other" count
/* Close our file */
fclose(inFile);
return 0;
}
Im trying to read in 2 .txt files containing integers sorted in ascending order into a third and I cannot use arrays. It works partially and then prints an infinite amount of squares. I believe this is an issue when the code gets to the end of one of the files.
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *n1, *n2, *op;
int c, d;
n1 = fopen("numbers1.txt", "r");
n2 = fopen("numbers2.txt", "r");
op = fopen("output.txt", "w");
c = fgetc(n1);
d = fgetc(n2);
while (1 )
{
if (c == EOF && d == EOF)
break;
else if (c<d )
{
putc(c, op);
c = fgetc(n1);
}
else if(d<c )
{
putc(d,op);
d = fgetc(n2);
}
else if(d == c )
{
putc(c, op);
c = fgetc(n1);
}
else if (c == EOF && d != EOF )
{
putc(d,op);
d = fgetc(n2);
}
else if (c != EOF && d == EOF )
{
putc(c, op);
c = fgetc(n1);
}
}
fclose(n1);
fclose(n2);
fclose(op);
}
#include <stdio.h>
#include <stdlib.h>
int main(void){
FILE *n1, *n2, *op;
int st1, st2;
int c, d;
n1 = fopen("numbers1.txt", "r");
n2 = fopen("numbers2.txt", "r");
op = fopen("output.txt", "w");
st1 = fscanf(n1, "%d", &c);
st2 = fscanf(n2, "%d", &d);
while(1){
if(st1 == EOF && st2 == EOF)
break;
if(st1 != EOF && st2 != EOF){
if(c < d){
fprintf(op, "%d\n", c);
st1 = fscanf(n1, "%d", &c);
} else if(c > d){
fprintf(op, "%d\n", d);
st2 = fscanf(n2, "%d", &d);
} else {
fprintf(op, "%d\n%d\n", c, d);
st1 = fscanf(n1, "%d", &c);
st2 = fscanf(n2, "%d", &d);
}
} else if(st1 != EOF){
fprintf(op, "%d\n", c);
st1 = fscanf(n1, "%d", &c);
} else {
fprintf(op, "%d\n", d);
st2 = fscanf(n2, "%d", &d);
}
}
fclose(n1);
fclose(n2);
fclose(op);
return 0;
}
The cleanest way to do this is to write three separate loops:
// Do the main loop until you reach the end of one of the files
while (!(c == EOF && d == EOF))
{
// do your stuff here
}
// At this point, at least one of the files is at EOF.
// You want to drain the other
// Note that only one of the two loops will be entered.
while (c != EOF)
{
// copy the remaining contents of the first file to the output
}
while (d != EOF)
{
// copy the remaining contents of the second file to the output
}
I know, it looks like more code. But you don't have all those if statements in the loop checking to see if you're at the end of the first file but not at the end of the other, etc. The above is a whole lot easier to understand, and you're more likely to get it right when you create it.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have the following text file
#1234
5,4
#tfxc
01AAX
11AA1
#tfxc
11AA1
11111
And I want to ignore the # and the data behind it when reading from the text file and the 5,4 are the dimensions of the matrix which I am storing in a 2d array.
This is my code:
#include <stdio.h>
FILE *inp;
int main(void) {
int i, j;
int y = 0;
int x = 0;
char comma;
char arr = 0;
inp = fopen("App.txt", "r");
fscanf(inp, "%d", &x);
fscanf(inp, "%c", &comma);
fscanf(inp, "%d", &y);
char array[y][x];
for (i = 0; i < y; i++) {
for (j = 0; j < x; j++) {
fscanf(inp, "%c", &arr);
if ((arr == '1') || (arr == 'X') || (arr == '0') || (arr == 'A')) {
array[i][j] = arr;
} else {
j--;
}
printf("%c", arr);
}
}
}
How I can do this?
Use fgets() to read lines, check if the line should be ignored, else parse the line to initialize your matrix.
Here is an example:
#include <stdio.h>
int main(void) {
int c, i, j, k, x = 0, y = 0;
char line[1024];
FILE *inp;
inp = fopen("App.txt", "r");
if (inp == NULL) {
printf("cannot open App.txt\n");
exit(1);
}
while (fgets(line, sizeof line, fp)) {
if (line[0] == '#') continue;
if (sscanf(line, "%d,%d", &x, &y) == 2)
break;
printf("invalid line: %s", line);
exit(1);
}
char array[y][x];
for (i = 0; i < y;) {
if (!fgets(line, sizeof line, inp)) {
printf("missing matrix data at row %d\n", i);
break;
}
if (line[0] == '#')
continue;
for (j = k = 0; j < x && line[k] != '\0'; k++) {
c = line[k];
if (c == '1' || c == 'X' || c == '0' || c == 'A') {
array[i][j] = c;
j++;
putchar(c);
}
}
putchar('\n');
if (j != x) {
printf("missing matrix values at %d,%d\n", i, j);
}
i++;
}
fclose(inp);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
int i, j;
int y = 0, x = 0;
FILE *inp = fopen("App.txt", "r");
if(!inp){
perror("fopen\n");
exit(EXIT_FAILURE);
}
while(2 != fscanf(inp, "%d,%d", &x, &y)){
int ch;
while((ch=fgetc(inp)) != '\n' && ch !=EOF);//skip
if(ch == EOF){
fprintf(stderr, "There is no dimension specified.\n");
exit(EXIT_FAILURE);
}
}
char array[y][x];
char format[32];
sprintf(format, "%%%d[01AX]%%c", x);
for (i = 0; i < y; i++) {
int status;
char newline = 0, buff[x+1];
status = fscanf(inp, format, buff, &newline);
if(status == 0 || status == 2 && newline != '\n'){//status 1 is OK
int ch;
while((ch=fgetc(inp)) != '\n' && ch !=EOF);//skip
--i;
continue;
}
if(status == EOF){
fprintf(stderr, "Necessary data is missing.\n");
exit(EXIT_FAILURE);
}
memcpy(array[i], buff, x);
}
fclose(inp);
//check print
for (i = 0; i < y; i++) {
for (j = 0; j < x; j++) {
putchar(array[i][j]);
}
putchar('\n');
}
return 0;
}
I'm trying to print escape characters as characters or strings using this code:
while((c = fgetc(fp))!= EOF)
{
if(c == '\0')
{
printf(" \0");
}
else if(c == '\a')
{
printf(" \a");
}
else if(c == '\b')
{
printf(" \b");
}
else if(c == '\f')
{
printf(" \f");
}
else if(c == '\n')
{
printf(" \n");
}
else if(c == '\r')
{
printf(" \r");
}
else if(c == '\t')
{
printf(" \t");
}
else if(c == '\v')
{
printf(" \v");
}
}
but when i try it, it actually prints the escape sequence.
Escape the slashes (use " \\a") so they won't get interpreted specially. Also you might want to use a lookup table or a switch at least.
switch (c) {
case '\0':
printf(" \\0");
break;
case '\a':
printf(" \\a");
break;
/* And so on. */
}
Backslashes in string literals need to be escaped; instead of "\0", you need "\\0".
A lookup table might make this less painful:
const char *ecs[256] = {NULL}; // assumes ASCII - may not be a valid assumption
int c;
ecs['\0'] = "\\0";
ecs['\a'] = "\\a";
ecs['\b'] = "\\b";
...
while ((c = fgetc(fp)) != EOF)
{
if (ecs[c] == NULL)
printf("%c", c);
else
printf("%s", ecs[c]);
}
Yes, the majority of entries in ecs are going to be NULL; the tradeoff is that I don't have to worry about mapping the character value to array index.
For that we need to use double backslash.
Examples:
if(c == '\0')
{
printf(" \\0");
}
else if(c == '\a')
{
printf(" \\a");
}
else if(c == '\b')
{
printf(" \\b");
}
else if(c == '\f')
{
printf(" \\f");
}
else if(c == '\n')
{
printf(" \\n");
}
else if(c == '\r')
{
printf(" \\r");
}
else if(c == '\t')
{
printf(" \\t");
}
else if(c == '\v')
{
printf(" \\v");
}
Should work for you!
If you want to escape %d within printf to allow you to actually print the characters "%d":
printf("%%d");