Существует множество способов собрать кусочки головоломки. Поиск инструмента для задания - это битва. В этом случае strtol
будет скрывать основание 2 до десятичного. Ключ должен распознавать, нет причин делать character input
, и вы можете упростить свой код, используя line-oriented input
, который предоставит ваши данные в формате, готовом для преобразования.
Ниже приведены фрагменты головоломки. Они несколько вышли из строя, так что вы можете работать, чтобы переупорядочить их для создания окончательного выходного файла с строкой и десятичным значением, содержащимся в ней. Вероятно, вы захотите открыть выходной файл перед чтением текстового файла, чтобы оба файла были доступны во время цикла чтения.
Посмотрите и дайте мне знать, если у вас есть вопросы. Примечание: это только один из многих, многих способов подойти к этой проблеме:
#include <stdio.h>
#include <stdlib.h>
#define MAXN 100
int main() {
char file_input[25] = { 0 }; /* always initialize all variables */
char file_output[25] = { 0 };
FILE *fi = NULL;
FILE *fo = NULL;
int integers[MAXN] = { 0 };
int i = 0;
int num = 0;
printf ("\n Please enter the input filename: ");
while (scanf ("%[^\n]%*c", file_input) != 1)
fprintf (stderr, "error: read failed for 'file_input', try again\n filename: ");
fi = fopen (file_input, "r"); /* open input file and validate */
if (!fi) {
perror ("Error while opening the file.\n");
exit (EXIT_FAILURE);
}
printf ("\n The contents of file '%s' are :\n\n", file_input);
char *line = NULL; /* NULL forces getline to allocate */
size_t n = 0; /* max chars to read (0 - no limit */
ssize_t nchr = 0; /* number of chars actually read */
while ((nchr = getline (&line, &n, fi)) != -1) {
if (line[nchr - 1] == '\n')
line[--nchr] = 0; /* strip newline from end of line */
integers[i] = strtol (line, NULL, 2); /* convert to decimal */
printf (" %s -> %d\n", line, integers[i]);
if (i == MAXN - 1) { /* check MAXN limit not exceeded */
fprintf (stderr, "error: input lines exceed %d\n", MAXN);
exit (EXIT_FAILURE);
}
i++;
}
if (line) free(line); /* free memory allocated by getline */
if (fi) fclose (fi); /* close file stream when done */
num = i; /* save number of elements in array */
printf ("\n Conversion complete, output filename: ");
while (scanf ("%[^\n]%*c", file_output) != 1)
fprintf (stderr, "error: read failed for 'file_output', try again\n filename: ");
fo = fopen (file_output, "w+"); /* open output file & validate */
if (!fo) {
perror ("Error while opening the file.\n");
exit (EXIT_FAILURE);
}
for (i = 0; i < num; i++) /* write integers to output file */
fprintf (fo, " %d\n", integers[i]);
if (fo) fclose (fo);
return 0;
}
Используйте/выход:
$ ./bin/arrayhelp
Please enter the input filename: dat/binin.txt
The contents of file 'dat/binin.txt' are :
01000101 -> 69
11010110 -> 214
11101110 -> 238
Conversion complete, output filename: dat/binout.txt
$ cat dat/binout.txt
69
214
238
Чтение символов за символом
Хотя это не самый простой способ справиться с чтением файла, в этом нет ничего плохого. Однако у вас есть логические проблемы. В частности, вы читаете (и назначаете как целое число) numi = ch;
, а затем назначаете numo = numi + 8;
для записи в выходной файл. Это приводит к тому, добавив к 8
ASCII значения '0'
() или '1'
(). Если вы добавите к этому, ну, вы можете сделать математику. Когда вы читаете из файла, как текст, вы читаете значение ASCII, НЕ числовое значение 1
или 0
.
Чтобы выполнить то, что вы пытаетесь сделать, вы должны сохранить все символы в строке в буфер (string
, a character array
, мне все равно, как вы это называете). Это единственный способ (вместо того, чтобы преобразовать по одному символу в числовой 1
или 0
, а затем предварительно сформировать binary addition
), вам необходимо преобразовать строку '0'
s и '1'
s в десятичное значение.
Вот пример, используя character-by-character
, читаемый от fi
. Прочтите это и поймите, почему это нужно сделать таким образом. Если у вас есть вопросы, оставьте еще один комментарий.
#include <stdio.h>
#include <stdlib.h>
#define MAXN 100
int main() {
int ch = 0;
FILE *fi = NULL;
FILE *fo = NULL;
// int numo = 0;
// int numi = 0;
// int nump = 0;
char buffer[MAXN] = { 0 }; /* buffer to hold each line */
int idx = 0; /* index for buffer */
fo = fopen ("OutputFile.txt", "w+"); /* open output file & validate */
if (!fo) {
perror ("Error while opening the file.\n");
exit (EXIT_FAILURE);
}
fi = fopen ("InputFile.txt", "r"); /* open input file & validate */
if (!fi) {
perror ("Error while opening the file.\n");
exit (EXIT_FAILURE);
}
printf ("\n The contents of %s file are :\n\n", "InputFile.txt");
fprintf (fo, " binary decimal\n"); /* header for output file */
while (1) /* loop and test for both '\n' and EOF (-1) to parse file */
{
// printf ("%c", ch); /* we will store each ch in line in buffer */
if ((ch = fgetc (fi)) == '\n' || ch == EOF)
{
if (ch == EOF && idx == 0) /* if EOF (-1) & buffer empty exit loop */
break;
buffer[idx] = 0; /* null-terminate buffer (same as '\0') */
idx = 0; /* reset index for next line & continue */
/* write original value & conversion to fo */
fprintf (fo, " %s => %ld\n", buffer, strtol (buffer, NULL, 2));
/* write fi contents to stdout (indented) */
printf (" %s\n", buffer);
}
else
{
buffer[idx++] = ch; /* assign ch to buffer, then increment idx */
}
/* This makes no sense. You are reading a character '0' or '1' from fi,
the unsigned integer value is either the ASCII value '0', which is
decimal 48 (or hex 0x30), or the ASCII value '1', decimal 49/0x31.
If you add 8 and write to 'fo' with '%d' you will get a 16-digit
string of a combination of '56' & '57', e.g. 56575756....
numi = ch;
numo = numi + 8;
*/
}
if (fi) /* close both input and output file streams */
fclose (fi);
if (fo)
fclose (fo);
return 0;
}
выход на стандартный вывод:
$ ./bin/arrayhelp2
The contents of InputFile.txt file are :
01000101
11010110
11101110
OutputFile.txt:
$ cat OutputFile.txt
binary decimal
01000101 => 69
11010110 => 214
11101110 => 238
Первая вещь, которую вы не знаете, как долго ваш файл, так что вам потребуется динамический выделение памяти ('malloc()', 'realloc()', 'free()') http://www.cplusplus.com/reference/cstdlib/malloc/. Вы динамически выделяете память 2D-массива (массив указателей на двоичный номер) http://stackoverflow.com/questions/19920452/dynamically-allocated-2-dimensional-array. После выполнения расчетов сохраните результаты в файле с помощью 'fprinf()' http://www.tutorialspoint.com/c_standard_library/c_function_fprintf.htm. –
Возможно, вам нужно сэкономить время и память и выполнить вычисления непосредственно после того, как вы прочтете целую строку. Надеюсь, что это поможет вам. –
Я отменил идею массива, и я получил SOMETHING для печати в OutputFile.txt. обновил код в исходном сообщении. – Zee